Fastest way to get count of unique elements in javascript array

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.


ES6 offers a single line solution:

new Set(myArray).size

Tags:

Javascript