Last active
April 13, 2020 17:31
-
-
Save amitk/493e8172f317bf834fdbb97ab2ff3084 to your computer and use it in GitHub Desktop.
remove duplicate elements from an array in javascript
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
arr = [5, 1, 3, 1, 4, 4, 5] | |
// using Set | |
/* Set is a new data structure introduced in ES6 which contains only unique elements */ | |
unique_arr = [...new Set(arr)] | |
// expanding the process | |
a_set = new Set(arr) // {5, 1, 3, 4} | |
unique_arr = Array.from(a_set) //[5, 1, 3, 4] | |
// using filter | |
unique_arr = arr.filter((ele, index) => arr.indexOf(ele) === index) | |
// indexOf returns first index of the element occurance, hence it will all the elements | |
//using reduce | |
unique_arr = arr.reduce((unique, ele) => unique.includes(ele) ? unique : [...unique, ele], []) | |
/* reduce function reduces a given array on the basis of some function passed, | |
Here, we are initializing a unique array whose initital value is []. Adding elements | |
one by one, by checking is that element already present in the array(unique) or not.*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment