COUNT UNIQUE NUMBERS JAVASCRIPT

PHOTO EMBED

Tue Dec 20 2022 09:44:37 GMT+0000 (Coordinated Universal Time)

Saved by @YaseenBhojani #javascript

// COUNT UNIQUE NUMBERS
// [1, 2, 2, 2, 3, 4, 4, 5, 6, 7, 8, 8]
// output -> 8
// conditions
// i = 0, j = 1
// array[i] !== array[j]
// 1. i++
// 2. array[i] = array[j]

const countUnique = (arr) => {
  if (arr.length > 0) {
    let i = 0;
    for (let j = 1; j < arr.length; j++) {
      if (arr[i] !== arr[j]) {
        i++; 
        arr[i] = arr[j];
      }
    }
    return i + 1;
  } else {
    throw new Error("Array is empty!");
  }
};

const result = countUnique([1, 2, 2, 2, 3, 4, 4, 5, 6, 7, 8, 8]);
console.log(result); // 8
content_copyCOPY