Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda