How to use Hash Map In Javascript
In this approach, we create an empty hash map object to store the count of occurrences of each element. Then we Iterate through the array and for each element we increment its count in the hash map. Then we will Iterate through the array again and for each element we check if its count in the hash map equals k, if it is we will return that element.
Example: The code below shows how we can find the first element that occurs k times using Hash Map.
function first_Element(arr, k) {
let hashMap_obj = {};
for (let i = 0; i < arr.length; i++) {
hashMap_obj[arr[i]] = (hashMap_obj[arr[i]] || 0) + 1;
}
for (let i = 0; i < arr.length; i++) {
if (hashMap_obj[arr[i]] === k) {
return arr[i];
}
}
return -1;
}
const arr = [3, 4,3, 9, 4, 2, 3, 6, 4];
const k = 3;
console.log(first_Element(arr, k));
Output
3
First Element to Occur K Times using JavaScript
Given an array and number, our task is to find the first element that occurs exactly k times in an array using JavaScript.
Example:
Input: array= [1, 2, 3, 4, 2, 5, 6, 4, 2] and k = 3.
Output: 2
Explanation: Here the first element that occurred 3 times in the array is 2
Table of Content
- Using nested for loop
- Using Hash Map