xxxxxxxxxx
//Other Mathod using Foreach and includes
let chars = ['A', 'B', 'A', 'C', 'B'];
let uniqueChars = [];
chars.forEach((c) => {
if (!uniqueChars.includes(c)) {
uniqueChars.push(c);
}
});
console.log(uniqueChars);
xxxxxxxxxx
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
let unique = [new Set(names)];
console.log(unique); // 'John', 'Paul', 'George', 'Ringo'
xxxxxxxxxx
let arr = [1,2,3,1,1,1,4,5]
let filtered = arr.filter((item,index) => arr.indexOf(item) === index)
console.log(filtered) // [1,2,3,4,5]
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
uniqueArray = a.filter(function(item, pos) {
return a.indexOf(item) == pos;
})
xxxxxxxxxx
const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [new Set(array)];
console.log(uniqueArray); // Output: [1, 2, 3, 5]
xxxxxxxxxx
uniqueArray = a.filter(function(item, pos) {
return a.indexOf(item) == pos;
})
xxxxxxxxxx
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
function removeDups(names) {
let unique = {};
names.forEach(function(i) {
if(!unique[i]) {
unique[i] = true;
}
});
return Object.keys(unique);
}
removeDups(names); // // 'John', 'Paul', 'George', 'Ringo'
xxxxxxxxxx
let chars = ['A', 'B', 'A', 'C', 'B'];
let uniqueChars = [new Set(chars)];
console.log(uniqueChars);
xxxxxxxxxx
[new Set(['1','1','2','2','3','3'])]
//this will return a new array with the unique primitive values
//I guess doing this with objects will require implementing equality method.