DEV Community

Dumb Down Demistifying Dev
Dumb Down Demistifying Dev

Posted on

Unique Values Counter

Implement a function CountUniqueValues, which takes in a sorted Array of positive and negative integers.
It should count and return the number of unique values in the Array.


  • This is an easy question.
  • It should be easily checked against using JavaScript.
  • It should try to use pointers to track the position of values to be compared against.
  • No need to mutate the original Array.
function CountUniqueValues(arr) {
    if (arr.length === 0) return 0;

    let uniqueValueIndex = 0;
    let counter = 1;

    for (let i = 1; i < arr.length; i++) {
        if (arr[i] !== arr[uniqueValueIndex]) {
            uniqueValueIndex = i;

    return counter;

// sample data
const sorted_array = [-10,-11,1,1,1,2,3,4,5,5,5,6,7,7,7,7,8];
// result
// to be asserted against result
console.warn(Array.from(new Set(sorted_array)).length);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)