Search This Blog

2026/08/09

Javascript : Find Duplicate using set




const arr = [4, 2, 7, 4, 2, 8, 4, 9];
let set = new Set();
const duplicates = new Set();

for (let i = 0; i < arr.length; i++) {
if (set.has(arr[i])) {
    duplicates.add(arr[i]);
} else {
    set.add(arr[i]);    
}
}

console.log("Duplicates", Array.from(duplicates));


Output:
Duplicates [ 4, 2 ]

Explanation:
1. We first initialize an empty set called `set` to store the unique values from the array
and another empty set called `duplicates` to store the duplicate values.
2. We then loop through the array and check if the current number is already present in the
 `set` using the `has()` method. If it is present, we add it to the `duplicates` set using the
 `add()` method. If it is not present, we add it to the `set` using the `add()` method.
3. Finally, we log the `duplicates` set to the console, which contains all the duplicate
 values found in the original array. We convert the set to an array using `Array.from()`  

No comments:

Post a Comment