Skip to content

Instantly share code, notes, and snippets.

@crates
Created March 19, 2020 21:36
Show Gist options
  • Save crates/cb241a52bc8d04eec2790d5309c31d26 to your computer and use it in GitHub Desktop.
Save crates/cb241a52bc8d04eec2790d5309c31d26 to your computer and use it in GitHub Desktop.
Javascript Array De-duplication (make items unique)
// 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