Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to get count of unique elements in javascript array

Tags:

javascript

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 (number of unique elements in array)

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

ANSWER: I used the .filter method as shown below. My actual array element is much more complex. I ended up iterating through my array and created a new array. Each element in the new array was a .substr of the old element. Then, the .filter method below worked great. THANKS to everyone!!

like image 666
hypermiler Avatar asked Feb 09 '14 16:02

hypermiler


People also ask

What is the best way to count unique values in JavaScript?

Pure Javascript, runs in O (n). Doesn't consume much space either unless your number of unique values equals number of elements (all the elements are unique). Same as this solution, but less code. let counts = {}; arr.forEach (el => counts [el] = 1 + (counts [el] || 0))

How to count elements of an array in JavaScript?

To count elements of an array in JavaScript, use the length property. The length property sets or returns the number of items in an array. The value of a length property is the integer with a positive sign and a value less than 2 to the 32nd power. To set the length of the array, use the array.length =number syntax.

How do you count unique elements in an array in Python?

A quick way to do this is to copy the unique elements into an Object. When this loop is complete the counts object will have the count of each distinct element of the array. The fast way to do this is with a new Set () object. Sets are awesome and we should use them more often.

How to count the number of occurrences of an array?

The .countBy () method in Lodash accepts an array and returns an object. This object contains elements and their counts as key-value pairs: If you need to count the number of occurrences of elements in an array, probably your best bet is to use the for-of loop as shown in this article.


2 Answers

You need to keep a set of known values, and an auxilliary count. 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 count of zero, this looks at each element to see whether it's been added to the set. If it hasn't, it's added, and the count is incremented.

like image 100
Pointy Avatar answered Oct 22 '22 08:10

Pointy


ES6 offers a single line solution:

new Set(myArray).size
like image 34
Postlagerkarte Avatar answered Oct 22 '22 09:10

Postlagerkarte