0

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? :)

2
  • inputArray.map(({Name,Id})=>({Name,count:Id})) Commented Jul 11, 2022 at 22:36
  • 3
    Please explain how this dude, Henry is all of a sudden in the output array when he wasn't in the input array? Commented Jul 11, 2022 at 22:40

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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
}, [])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.