how to remove the duplicate elements in an array in JS code example
Example 1: javascript to remove duplicates from an array
uniqueArray = a.filter(function(item, pos) {
return a.indexOf(item) == pos;
})
Example 2: use set to remove duplicates in javascript
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'