DEV Community

Discussion on: Tackling Algorithms: Counting Unique Values

Collapse
 
gmartigny profile image
Guillaume Martigny

One clever solution is to use Set as they have unique values by design:

function countUniqueValues(arr) {
  return new Set(arr).size;
}
countUniqueValues([]); // => 0
countUniqueValues([1, 1, 1, 2, 3, 3]); // => 3

It's not really an algorithm, tho ;)

Collapse
 
denisepen profile image
Denise Pen

Right... I always forget about sets!

That makes everything so much easier.

Collapse
 
anndd profile image
Anna Su** • Edited

... and a lazy solution would be to use underscorejs:

_.uniq([1, 1, 1, 2, 3, 3]).length; //=> 3
Collapse
 
jlarrieux profile image
Jean-Rodney Larrieux

My code wouldn't have been that concise but exact solution I thought of