Skip to content

Instantly share code, notes, and snippets.

@CharmedSatyr
Last active July 28, 2018 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CharmedSatyr/f20bdc6c42fc2e7e8c2f3c8053089466 to your computer and use it in GitHub Desktop.
Save CharmedSatyr/f20bdc6c42fc2e7e8c2f3c8053089466 to your computer and use it in GitHub Desktop.
Deduplicate Array
// METHOD 1: reduce/indexOf
//`uniques` contains one of each unique value in `arr`
let arr = ['ant', 0, 'aunt', 'ant'];
let uniques = arr.reduce((acc, curr) => {
if (acc.indexOf(curr) < 0) {
acc.push(curr);
}
return acc;
}, []);
console.log(uniques); // ['ant', 0, 'aunt']
// METHOD 2: Array.from/new Set
const uniq = a => Array.from(new Set(a));
const dupArr = [0, 1, 0, 2, { a: 'a' }, 1, 'a', 'a', 10, 12, 'ab', 'b'];
console.log(uniq(dupArr)); // [0, 1, 2, { a: 'a' }, 'a', 10, 12, 'ab', 'b']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment