Skip to content

Instantly share code, notes, and snippets.

@hoyangtsai
Created December 27, 2021 06:20
Show Gist options
  • Save hoyangtsai/611d0c3a41d83bea956fa204980414bc to your computer and use it in GitHub Desktop.
Save hoyangtsai/611d0c3a41d83bea956fa204980414bc to your computer and use it in GitHub Desktop.
Remove duplicates from an array
// 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'
@hoyangtsai
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment