I have an array of objects with students name which are getting repeated often. I want to create a frequency counter of the students name with the number of total counts.
Array :
arr = [
{
name: 'Akshay',
age: '15',
},
{
name: 'Rajat',
age: '14',
},
{
name: 'Akshay',
age: '16',
},
{
name: 'Sam',
age: '12',
},
{
name: 'Akshay',
age: '11',
},
{
name: 'Rajat',
age: '17',
},
{
name: 'Akshay',
age: '12',
},
{
name: 'Sam',
age: '18',
},
{
name: 'Sam',
age: '19',
}
]
I want to get the result like this in an array
result = [
{
name: 'Akshay',
count: 4
},
{
name: 'Rajat',
count: 2
},
{
name: 'Sam',
count: 3
},
]
I tried the below solution but it's not working properly -
const result = arr.reduce((counter,item) => {
var getItem = item.name;
counter[getItem] = counter.hasOwnProperty(getItem) ? counter[getItem] : 1;
return counter;
})
Please help.
reducewith an initial value, an empty object. And you should increment the previous value.reducecall is missing the initial value (use{}), and you need to convert the result to the array that you're looking for. Apart from those the approach is fine.