0

Can someone explains step by step the following function? I lost it when the body of the reduce begins:

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')
4
  • how about putting console.log everywhere and tracking what the code does? Commented Feb 23, 2020 at 17:38
  • @grodzi - Or, rather than stumbling around in the dark with a console.log torch, he could turn on the lights using the debugger built into his IDE or browser. Commented Feb 23, 2020 at 17:39
  • @grodzi I've done it, but can't get the logic... Commented Feb 23, 2020 at 17:52
  • 1
    @T.J. Crowder , thank you sir for your answer. If you want it you can answer my question with the solution you already provided, please. Commented Feb 23, 2020 at 17:53

1 Answer 1

2

reduce makes that function more complex-seeming than it actually is. (reduce is hugely overused, and almost always the wrong tool vs. a simple loop unless you're doing functional programming with predefined, reusable reducer functions.) Here's the same function without the unnecessary reduce, with explanation:

function groupBy(objectArray, property) {
  // The object we'll return with properties for the groups
  let result = {}
  // Loop through the array
  for (const obj of objectArray) {
    // Get the key value
    let key = obj[property]
    // If the result doesn't have an entry for that yet, create one
    if (!result[key]) {
      result[key] = []
    }
    // Add this entry to that entry
    result[key].push(obj)
  }
  // Return the grouped result
  return result
}

The reduce version just passes result around (as acc): reduce calls the callback with the initial value (the {} you see near the end of the reduce call) and the first entry, which the callback receives as acc and obj. Then the callback does one entry's work and returns acc, which means it receives it again on the next pass.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.