Created
March 19, 2020 21:36
-
-
Save crates/cb241a52bc8d04eec2790d5309c31d26 to your computer and use it in GitHub Desktop.
Javascript Array De-duplication (make items unique)
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
// There are a lot of ways to handle this need. This one is great for performance in all envs. | |
const removeDups = xs => { | |
const collect = (r, x) => { | |
if (!r.seen[x]) { | |
r.result.push(x); | |
r.seen[x] = true; | |
} | |
return r; | |
}; | |
return xs.reduce(collect, { seen: {}, result: [] }).result; | |
}; | |
const xs = [10, 23, 23, 22, 10, 3, 3, 4, 5]; | |
console.log(removeDups(xs)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment