Header Ads Widget

Responsive Advertisement

03:Javascript Dsa problem | count unique element in array

    Count unique elements in array |JS

Q:) We have an array of elements and we have to find out how many elements in the array are unique?

 Sol:) 

var arr = [1, 1, 2, 2, 3, 42];
let i = 0;
for (let j = 1; j <= arr.length; j++) {// 1
    // console.log(arr[i])
    if (arr[i] !== arr[j]) {
        i++;
        arr[i] = arr[j];
    };
};
console.log(i, "unique element==")

 
here is the code we can solve the problem and generate the desired result, Let's break it down step by step:

1:Array Initialization:

var arr = [1, 1, 2, 2, 3, 42]:
This line initializes an array named "arr" with some elements [1, 1, 2, 2, 3, 42].

2:Variable Declaration:

let i = 0;

 This line declares a variable "i" and initializes it with the value 0. This variable will be used as an index to keep track of unique elements in the array.

3: Loop Execution:

for (let j = 1; j <= arr.length; j++) {:

 This line starts a loop that iterates over the array elements. It initializes "j" with 1 and continues the loop until j becomes equal to the length of the array.

4: Conditional Check  below:

if (arr[i] !== arr[j]) {:
 This line checks if the element at index "i" is not equal to the element at index "j" in the array arr. If they are not equal, it implies that a new unique element is found.

5: Updating Index and Array:

  i++;
 If a new unique element is found, the index "i" is incremented by 1. This indicates that a new unique element is added to the array.

arr[i] = arr[j];
 The element at index "j" is assigned to the index "i" in the array "arr". This effectively replaces the duplicate element at index "i" with the unique element at index "j".

6: Loop Continuation:

The loop continues until "j" reaches the end of the array.

7: Logging Unique Element Count:

console.log(i, "unique element==")

After the loop completes, the number of unique elements is logged to the console along with the message "unique element".

Summary

We aim to find unique elements in the array "arr" and modify the array in place to contain only the unique elements.
It uses two indices "i" and "j" to iterate through the array, compares adjacent elements to identify duplicates, and updates the array to retain only the unique elements.
Finally, it logs the count of unique elements to the console.

  

Feel free to reach out and drop your query.
if you have a better idea to solve this question then let us know in the comment section

Post a Comment

0 Comments