The code is something like this:
let inputArray=[
{Id: '1', Name: 'Ani'},
{Id: '2', Name: 'George'},
{Id: '4', Name: 'George'},
{Id: '5', Name: 'Ani'}];
I need to make a new array with objects in the format :
let result=[
{ Name: 'Ani', count:2},
{ Name: 'George',count:2},
{ Name: 'Henry',count:1}];
Any idea please? :)
You can try to use a Hash & Array.reduce here.
const hash = inputArray.reduce((memo, item) => {
memo[item.Name] = memo[item.Name] || {name: item.Name, count: 0}
memo[item.Name].count++
return memo
}, {})
result = Object.values(hash)
You can use this function to count the repetition of any field given the field name
let inputArray=[
{Id: '1', Name: 'Ani'},
{Id: '2', Name: 'George'},
{Id: '4', Name: 'George'},
{Id: '5', Name: 'Ani'}];
function countFields(input, field){
const count = {};
input.forEach(e =>{
const v = e[field];
if(!count[v])count[v] = 0;
count[v]++;
})
return count;
}
const result = countFields(inputArray, "Name")
console.log(result)
Another solution with reduce:
let inputArray = [
{Id: '1', Name: 'Ani'},
{Id: '2', Name: 'George'},
{Id: '4', Name: 'George'},
{Id: '5', Name: 'Ani'}];
const counts = inputArray.reduce((acc, curr) => {
const valIndex = acc.findIndex(val => val.name === curr.Name)
if(valIndex >= 0) {acc[valIndex].count += 1}
else {
acc.push({name: curr.Name, count: 1})
}
return acc
}, [])