Skip to content

Instantly share code, notes, and snippets.

@amitk
Last active April 13, 2020 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitk/493e8172f317bf834fdbb97ab2ff3084 to your computer and use it in GitHub Desktop.
Save amitk/493e8172f317bf834fdbb97ab2ff3084 to your computer and use it in GitHub Desktop.
remove duplicate elements from an array in javascript
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