Skip to content

Instantly share code, notes, and snippets.

@masautt
Created September 6, 2019 18:20
Show Gist options
  • Save masautt/4ce6ca53bce681831d7fcba66c96d304 to your computer and use it in GitHub Desktop.
Save masautt/4ce6ca53bce681831d7fcba66c96d304 to your computer and use it in GitHub Desktop.
How to remove duplicates from an array in JavaScript?
// Using Sets
function removeDupes(arr) {
return [...new Set(arr)];
}
// Using filter( )
function removeDupes1(arr) {
return arr.filter((v,i) => arr.indexOf(v) === i)
}
// Using forEach( )
function removeDupes2(arr) {
let unique = {};
arr.forEach(function(i) {
if(!unique[i]) {
unique[i] = true;
}
});
return Object.keys(unique);
}
console.log(removeDupes(["M", "A", "R", "E", "K", "S", "A", "U", "T", "T", "E", "R"])); // --> [ 'M', 'A', 'R', 'E', 'K', 'S', 'U', 'T' ]
console.log(removeDupes1(["M", "A", "R", "E", "K", "S", "A", "U", "T", "T", "E", "R"])); // --> [ 'M', 'A', 'R', 'E', 'K', 'S', 'U', 'T' ]
console.log(removeDupes2(["M", "A", "R", "E", "K", "S", "A", "U", "T", "T", "E", "R"])); // --> [ 'M', 'A', 'R', 'E', 'K', 'S', 'U', 'T' ]
// https://wsvincent.com/javascript-remove-duplicates-array/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment