Find duplicate in an array using hashmap.
Code:
const arr = [4, 2, 7, 4, 2, 8, 4, 9];
const hashMap = new Map();
for (const num of arr) {
if (hashMap.has(num)) {
let count = hashMap.get(num);
hashMap.set(num, count + 1);
} else {
hashMap.set(num, 1);
}
}
console.log("Ocuurance of numbers:", hashMap);
const duplicates = Array.from(hashMap)
.filter(([key, value]) => value > 1)
.map(([key, value]) => key);
console.log("Duplicates occur for :",duplicates);
output:
Ocuurance of numbers: Map(5) { 4 => 3, 2 => 2, 7 => 1, 8 => 1, 9 => 1 }
Duplicates occur for : [ 4, 2 ]
Explanation:
1. We first initialize an empty hashmap using the `Map()` constructor.
2. We then loop through the array and check if the current number is
already present in the hashmap using the `has()` method. If it is present,
we increment its count by 1 using the `get()` and `set()` methods.
If it is not present, we add it to the hashmap with a count of 1 using the `set()` method.
3. After processing the entire array, we log the hashmap to the console, which contains
the occurrence of each number in the array.
4. We then use the `Array.from()` method to convert the hashmap into an array of key-value
pairs, and filter out the pairs where the value (count) is greater than 1, indicating that
the number is a duplicate. We then use the `map()` method to extract the keys (numbers)
from the filtered pairs and store them in a new array called `duplicates`.
5. Finally, we log the `duplicates` array to the console, which contains all the duplicate
values found in the original array.
No comments:
Post a Comment