0

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 }]
// }
5
  • 1
    "I tried to console log the typeof acc" - can you show us how, please? "but it is undefined" - no it's not Commented Mar 29, 2022 at 18:41
  • 1
    Are you asking about the reduce in general or just about the if (!acc[key]) condition in particular? Commented Mar 29, 2022 at 18:42
  • @Bergi both I guess, I read and full MDN reduce() documentation and tried some of the programs but still not confident in using reduce method, any suggestions, please? Thank you. Commented Mar 30, 2022 at 4:49
  • I'd suggest not to use it in this case. The accumulator stays the same, using reduce is kinda pointless here. Use a normal loop: const acc = {}; for (const obj of objectArray) { … } return acc; Commented Mar 30, 2022 at 4:52
  • @Bergi Okay, Thanks Commented Mar 30, 2022 at 5:12

1 Answer 1

1

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.

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.