DEV Community

Tackling Algorithms: Counting Unique Values

Denise Pen on February 04, 2019

Problem: Given an array of integers, count the number of unique values. For example, if we have the following array: [1, 1, 1, 1, 1, 1...
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
 
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
 
denisepen profile image
Denise Pen

Right... I always forget about sets!

That makes everything so much easier.

Collapse
 
jlarrieux profile image
Jean-Rodney Larrieux

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

Collapse
 
adtm profile image
Tomas Eglinskas

I think also you could use this technique I wrote in this post: dev.to/adtm/whats-your-favorite-al... :)

negating numbers on the fly and checking if they exist, if it doesn't - add +1 to the counter.

Collapse
 
darkain profile image
Vincent Milum Jr

What happens when the array isn't pre-sorted?

Collapse
 
denisepen profile image
Denise Pen

If it's not pre-sorted you have to use a different approach - the multiple pointers approach won't work.