DEV Community

Discussion on: 👨🏻‍💻 UnderStand the Most Powerful 💪 Function of Javascript

Collapse
 
jpantunes profile image
JP Antunes

A better example of what you can do with reduce is group objects by property. Case in point, here's how to split the students by result:

students.reduce( (acc, val) => {
    !acc[val.result] 
        ? acc[val.result] = [val.name] 
        : acc[val.result].push(val.name); 
    return acc; 
}, {})

Produces:

{ Fail: [ 'Kushal' ], Pass: [ 'Rahul', 'Kushal' ] }
Collapse
 
jpantunes profile image
JP Antunes

Another interesting use case for reduce is to create a lookup table from an object and a property / key.

let phoneBook = students.reduce( (acc, val) => (acc[val.mobileNo] = val, acc), {})

> phoneBook[989481]
{ name: 'Kushal',
  class: 'MCA',
  result: 'Pass',
  mobileNo: '989481' }