Given an array of objects and the task is to find the occurrences of a given key according to its value.
Example:
Input : arr = [
{
employeeName: "Ram",
employeeId: 23
},
{
employeeName: "Shyam",
employeeId: 24
},
{
employeeName: "Ram",
employeeId: 21
},
{
employeeName: "Ram",
employeeId: 25
},
{
employeeName: "Kisan",
employeeId: 22
},
{
employeeName: "Shyam",
employeeId: 20
}
]
key = "employeeName"
Output: [
{employeeName: "Ram", occurrences: 3},
{employeeName: "Shyam", occurrences: 2},
{employeeName: "Kisan", occurrences: 1}
]
Approach: In this approach, we follow the steps below.
- Create an empty output array.
- Using the forEach iterate the input array.
- Check if the output array contains any object which contains the provided key’s value
- If not, then create a new object and initialize the object with the key(the provided key name) set to value (the key’s value of the object of the present iteration) and occurrence set to value 1
- If yes, then iterate the output array and search if the key of the present iteration is equal to the key of the input array iteration then increase the occurrence to 1.
Example:
Javascript
<script>
function findOcc(arr, key){
let arr2 = [];
arr.forEach((x)=>{
if (arr2.some((val)=>{ return val[key] == x[key] })){
arr2.forEach((k)=>{
if (k[key] === x[key]){
k[ "occurrence" ]++
}
})
} else {
let a = {}
a[key] = x[key]
a[ "occurrence" ] = 1
arr2.push(a);
}
})
return arr2
}
let arr = [
{
employeeName: "Ram" ,
employeeId: 23
},
{
employeeName: "Shyam" ,
employeeId: 24
},
{
employeeName: "Ram" ,
employeeId: 21
},
{
employeeName: "Ram" ,
employeeId: 25
},
{
employeeName: "Kisan" ,
employeeId: 22
},
{
employeeName: "Shyam" ,
employeeId: 20
}
]
let key = "employeeName"
console.log(findOcc(arr, key))
</script>
|
Output:
[
{
employeeName: "Ram",
occurrence: 3
},
{
employeeName: "Shyam",
occurrence: 2
},
{
employeeName: "Kisan",
occurrence: 1
}
]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
19 Dec, 2022
Like Article
Save Article