Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
How to transform array of objects to new array of objects and count the keys

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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)
about 4 years ago · Juan Pablo Isaza Report

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)

about 4 years ago · Juan Pablo Isaza Report

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
}, [])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!