The fastest way to get the number of unique elements in a javascript array

I need to find the number of unique elements in an array.

var myArray = [ 10, 10, 20, 20, 30, 30, 40, 40, 40, 40, 50, 50, 50, 50, 60 ]; 

I want count = 6 (the number of unique elements in the array)

And is there a way to do this without iterating through an array? (I guess this would be the fastest way?).

ANSWER: I used the .filter method as shown below. My actual array element is much more complicated. I finished the iteration through my array and created a new array. Each element of the new array was a .substr of the old element. Then the .filter method below worked fine. THANKS to everyone!

+7
source share
4 answers

You need to save a set of known values ​​and an auxiliary account. You can use .reduce() :

 var count = myArray.reduce(function(values, v) { if (!values.set[v]) { values.set[v] = 1; values.count++; } return values; }, { set: {}, count: 0 }).count; 

Starting with an empty set of values ​​and a zero count, it looks at each element to see if it is added to the set. If this is not the case, it is added and the score is increased.

+6
source

How about filter and length:

 var len = myArray.filter(function(val, i, arr) { return arr.indexOf(val) === i; }).length; 
+5
source

If you are using lodash:

 _.uniq(myArray).length 
+1
source

ES6 offers a single-line solution:

 Array.from(new Set(myArray)).length 
0
source

All Articles