Javascript Program to Count Unique Elements in an array

Javascript Program to Count Unique Elements in an array

Problem Statement: In this program, we will be learning to count unique elements in an array using javascript. Let us take a simple example where we have an array with a lot of repetitive elements or numbers and you need to just tell the user the count of unique numbers by just creating a countUnique function in Javascript.

For reference, we have given an example below with output so that you can understand the problem statement properly.

Examples
Example 1:
Input: array[] = {1,2,2,3,4,4,5,6,7,8,8}
Output: 8 
Explanation: By seeing the array it is clearly visible that 2,4 and 8 are 
repeated 2 times each. So in total the unique elements in the array stand 
out to be 8 

Example 2:
Input: array[] = {1,2,2,3,3,4,4,5,5,8,8}
Output: 6
Explanation: By seeing the array it is clearly visible that 2,3,4,5 and 8 
are repeated 2 times each. So in total the unique elements in the array 
stand out to be 6
Javascript Code
function countUnique(array){
if(array.length>0){
let i=0;
for(let j=1;j<array.length;j++){
if(array[i]!=array[j]){
i++;
array[i] = array[j];
}
}
return i+1;
}
else{
throw new Error("Array is Empty");
}
}
const result = uniqueCount([1,2,2,3,3,4,4,5,5,8,8])
console.log(result)

In the above code, we have created two variables i and j. And i is pointing to the first element of the array and j is pointing to the second element of the array when the program starts. Other than that we are also checking whether the array is empty or not also at the start of the program. If the value of i and j matches then we are just incrementing the value of j by 1.

If they don’t then we are just incrementing the value of i by 1 and the value of j with i (i.e done by using the following code array[i]=array[j]). If the array is empty then we are just throwing an error and if it is not then we are counting the unique elements in the array for which the logic is already described above. At last we are just returning the last value of i + 1 which will generally give you the no of unique elements in the array.

Note : The array should always be in a sorted order to get the desired 
output easily. If it is not then we should sort the array first.
Output:
8
Time Complexity : O(n)

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay Connected

0FansLike
3,802FollowersFollow
19,400SubscribersSubscribe
- Advertisement -spot_img

Latest Articles