Last active
January 5, 2024 04:53
-
-
Save gotraveltoworld/4a372d567e8f2c1639cd7e9431d16d50 to your computer and use it in GitHub Desktop.
How to remove duplicates in JS.
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
// 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