Skip to content

Instantly share code, notes, and snippets.

@gotraveltoworld
Last active January 5, 2024 04:53
Show Gist options
  • Save gotraveltoworld/4a372d567e8f2c1639cd7e9431d16d50 to your computer and use it in GitHub Desktop.
Save gotraveltoworld/4a372d567e8f2c1639cd7e9431d16d50 to your computer and use it in GitHub Desktop.
How to remove duplicates in JS.
// Reference: https://codepen.io/macmladen/pen/XBwgEa/
let arr = [1, 2, 3, 4, 5, 1, 2 ,3, 4, 5];
// Set, this is a simple and plain method.
[...new Set(arr)];
// filter, a built-in method based on the filter function.
arr.filter((item, index) => arr.indexOf(item) === index);
// Retrieve the duplicate values
arr.filter((item, index) => arr.indexOf(item) !== index);
// reduce. a built-in method based on the reduce function.
arr.reduce((unique, item) => unique.includes(item) ? unique : [...unique, item], []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment