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

269
Vistas
Array reduce not giving all the data

let inputArr = [{
    "gender": "MALE",
    "name": "A",
    "age": 20
  },
  {
    "gender": "MALE",
    "name": "B",
    "age": 12
  },
  {
    "gender": "FEMALE",
    "name": "C",
    "age": 16
  },
  {
    "gender": "MALE",
    "name": "D",
    "age": 21
  },
  {
    "gender": "FEMALE",
    "name": "E",
    "age": 30
  }
]
console.log(JSON.stringify(inputArr.reduce((acc, ele) => {

  if (acc[ele["gender"]]) {
    acc[ele.gender].members.push(ele);
  } else {

    acc[ele["gender"]] = {
      members: []
    }
  }
  return acc;
}, {})))

I am trying to group users on the basis of gender ,using Array.reduce but the output is not showing all the records that are included in the array ,I am not able to understand the isssue here

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Your reducer doesn't push the element when it encounter a gender for the first time, so the first user of each gender is missing from your result

let inputArr = [{"gender": "MALE","name": "A","age": 20},{"gender": "MALE","name": "B","age": 12},{"gender": "FEMALE","name": "C","age": 16},{"gender": "MALE","name": "D","age": 21},{"gender": "FEMALE","name": "E","age": 30}]

console.log(JSON.stringify(inputArr.reduce((acc, ele) => {

  if (acc[ele["gender"]]) {
    acc[ele.gender].members.push(ele);
  } else {

    acc[ele["gender"]] = {
      members: [ele] // initialise the array with the current user
    }
  }
  return acc;
}, {})))

about 4 years ago · Juan Pablo Isaza Denunciar

0

Another solution, but I don't recommend this if performance matter.

let inputArr = [{
    "gender": "MALE",
    "name": "A",
    "age": 20
  },
  {
    "gender": "MALE",
    "name": "B",
    "age": 12
  },
  {
    "gender": "FEMALE",
    "name": "C",
    "age": 16
  },
  {
    "gender": "MALE",
    "name": "D",
    "age": 21
  },
  {
    "gender": "FEMALE",
    "name": "E",
    "age": 30
  }
]

function groupBy(array, field) {
  return array.reduce((acc, item) => ({
    ...acc,
    [item[field]]: [...acc[item[field]] || [], item]
  }), {})
}

console.log(groupBy(inputArr, "gender"))

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