Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an array of unique values from an array containing duplicates in JavaScript? [duplicate]

Given a ['0','1','1','2','3','3','3'] array, the result should be ['0','1','2','3'].

like image 667
NaveenDAlmeida Avatar asked Nov 21 '12 04:11

NaveenDAlmeida


People also ask

How do you get all unique values remove duplicates in a JavaScript array?

To find a unique array and remove all the duplicates from the array in JavaScript, use the new Set() constructor and pass the array that will return the array with unique values. There are other approaches like: Using new ES6 feature: [… new Set( [1, 1, 2] )];

How do I get unique elements from an array?

By using hashmap's key. In Java, the simplest way to get unique elements from the array is by putting all elements of the array into hashmap's key and then print the keySet(). The hashmap contains only unique keys, so it will automatically remove that duplicate element from the hashmap keySet.


1 Answers

Edited

ES6 solution:

[...new Set(a)]; 

Alternative:

Array.from(new Set(a)); 

Old response. O(n^2) (do not use it with large arrays!)

var arrayUnique = function(a) {     return a.reduce(function(p, c) {         if (p.indexOf(c) < 0) p.push(c);         return p;     }, []); }; 
like image 72
Pedro L. Avatar answered Oct 21 '22 22:10

Pedro L.