xxxxxxxxxx
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
let unique = [new Set(names)];
console.log(unique);
xxxxxxxxxx
// how to remove duplicates from array in javascript
// 1. filter()
let num = [1, 2, 3, 3, 4, 4, 5, 5, 6];
let filtered = num.filter((a, b) => num.indexOf(a) === b)
console.log(filtered);
// Result: [ 1, 2, 3, 4, 5, 6 ]
// 2. Set()
const removeDuplicates = (arr) => [new Set(arr)];
console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
// Result: [ 1, 2, 3, 4, 5, 6 ]
xxxxxxxxxx
const array = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// or
const nonUnique = [new Set(array)];
// Output: [5, 4, 7, 8, 9, 2]
xxxxxxxxxx
uniqueArray = a.filter(function(item, pos) {
return a.indexOf(item) == pos;
})
xxxxxxxxxx
uniqueArray = a.filter(function(item, pos) {
return a.indexOf(item) == pos;
})
xxxxxxxxxx
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
// usage example:
let a = ['a', 1, 'a', 2, '1'];
let unique = a.filter(onlyUnique);
console.log(unique); // ['a', 1, 2, '1']
xxxxxxxxxx
let chars = ['A', 'B', 'A', 'C', 'B'];
let uniqueChars = [new Set(chars)];
console.log(uniqueChars);
xxxxxxxxxx
const removeDuplicateStrings = (array) => {
const uniqueValues = [];
const seenMap = {};
for (const item of array) {
if (seenMap[item]) continue;
seenMap[item] = true;
uniqueValues.push(item);
}
return uniqueValues;
};
// or
const removeDuplicates = (array) => {
// Turn our array into a Set, which can only contain
// unique values, and then make an array from that set.
return [new Set(array)];
};
xxxxxxxxxx
var car = ["Saab","Volvo","BMW","Saab","BMW",];
var cars = [new Set(car)]
document.getElementById("demo").innerHTML = cars;