Created
December 27, 2021 06:20
-
-
Save hoyangtsai/611d0c3a41d83bea956fa204980414bc to your computer and use it in GitHub Desktop.
Remove duplicates from an array
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
// use Set | |
const names = ['John', 'Paul', 'George', 'Ringo', 'John']; | |
let unique = [...new Set(names)]; | |
console.log(unique); // 'John', 'Paul', 'George', 'Ringo' | |
// use Filter | |
const names = ['John', 'Paul', 'George', 'Ringo', 'John']; | |
let x = (names) => names.filter((v,i) => names.indexOf(v) === i) | |
x(names); // 'John', 'Paul', 'George', 'Ringo' | |
// use ForEach | |
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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code from JavaScript: Remove Duplicates from an Array - William Vincent