Last active
July 28, 2018 00:00
-
-
Save CharmedSatyr/f20bdc6c42fc2e7e8c2f3c8053089466 to your computer and use it in GitHub Desktop.
Deduplicate Array
This file contains 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
// 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