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

98
Views
Can JS experts explain me this if conditional logic array reduce method?

I'm not getting the logic written in if condition, I tried to console log the typeof acc, but it is undefined

let people = [
  { name: 'Alice', age: 21 },
  { name: 'Max', age: 20 },
  { name: 'Jane', age: 20 }
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    let key = obj[property]
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(obj)
    return acc
  }, {})
}

let groupedPeople = groupBy(people, 'age')
// groupedPeople is:
// {
//   20: [
//     { name: 'Max', age: 20 },
//     { name: 'Jane', age: 20 }
//   ],
//   21: [{ name: 'Alice', age: 21 }]
// }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The reduce is grouping by certain property. This involves creating arrays in the object keyed by each grouping and pushing the items into the array. If one particular item is the first member of its group encountered in the course of iterating, there will not yet be an array at the key to push to. Thus--

if (!acc[key]) {
  acc[key] = []
}

-- checks to see if there is an array available yet at the key to push to. If not, then it will add an array at the key for group members to be added to. So, this if condition will only evaluate as true a single time for each group-- the very first time a member of the group is encountered.

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!