Created
September 6, 2019 18:20
-
-
Save masautt/4ce6ca53bce681831d7fcba66c96d304 to your computer and use it in GitHub Desktop.
How to remove duplicates from an array in JavaScript?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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