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

276
Views
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 answers
Answer question

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 Report

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 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!