Home > Software engineering >  How to write this function with forEach?
How to write this function with forEach?

Time:08-10

I am trying to group the people by their age and as you can see, my code works with the reduce method. I managed to get this working but now I want to do the same with forEach method. Here's my code:

    {name:'Kyle', age:42},
    {name:'Suk', age:34},
    {name:'Lol', age:35},
    {name:'Pol', age:23},
    {name:'Kol', age:23}
]


people.reduce((groupedPeople, person)=>{
    const age = person.age
    if(groupedPeople[age] == null) {groupedPeople[age]=[]
    }
    groupedPeople[age].push(person)
    return groupedPeople
})

CodePudding user response:

Reduce accepts initial value that you update each iteration and return. So if you wish to use forEach, just move initial value before the forEach:

const people = [{
    name: 'Kyle',
    age: 42
  },
  {
    name: 'Suk',
    age: 34
  },
  {
    name: 'Lol',
    age: 35
  },
  {
    name: 'Pol',
    age: 23
  },
  {
    name: 'Kol',
    age: 23
  }
]


const groupedPeople = {}
people.forEach((person) => {
  const age = person.age
  if (groupedPeople[age] == null) {
    groupedPeople[age] = []
  }
  groupedPeople[age].push(person)
})

console.log(groupedPeople)

However, I am not sure why you wish to do that. Code with reduce is much cleaner.

CodePudding user response:

Why forEach is just reduce with an accumulative value. Might as well be "global".

var people =  [
  {name:'Kyle', age:42},
  {name:'Suk', age:34},
  {name:'Lol', age:35},
  {name:'Pol', age:23},
  {name:'Kol', age:23}
];

var result = people.reduce((groupedPeople, person) => {
  const age = person.age
  if (groupedPeople[age] == null) {
    groupedPeople[age] = []
  }
  groupedPeople[age].push(person)
  return groupedPeople
}, {}) //  <---- you forgot this {}
console.log(result)

var result = {};
people.forEach(function(person) {
  if (result[person.age] == null) {
    result[person.age] = []
  }
  result[person.age].push(person)
})

console.log(result)
.as-console-wrapper {
  max-height: 100%!important;
  top: 0;
}

  • Related