r/learnjavascript • • Mar 24 '20

Array Reduce Explained in 80 Seconds

https://youtu.be/lxT4LZdtJrU
70 Upvotes

25 comments sorted by

View all comments

5

u/[deleted] Mar 24 '20

mdn explains this shit better than any of these silly videos

7

u/Macaframa Mar 24 '20 edited Mar 27 '20

All of these tutorials are super misleading as they don’t even begin to touch on how useful the reduce method really is. I usually use the example of grouping items by type.

const items = [
  {
    name: “toilet paper”,
    type: “bathroom”,
    amount: 3,
    price: 13
  },
  {
    name: “tooth brush”,
    type: “bathroom”,
    amount: 1,
    price: 6
  },
  {
    name: “67 piece cutlery set”,
    type: “kitchen”,
    amount: 1,
    price: 117
  },
  {
    name: “8 pack black ballpoint pens”,
    type: “office”,
    amount: 1,
    price: 4
  },
  {
    name: “post it notes”,
    type: “office”,
    amount: 2,
    price: 3
  }
];

const orderGroupedByType = items.reduce((accumulator, {name, type, amount, price}) => {
  if(!accumulator[type]) {
    accumulator[type] = [];
  }
  accumulator[type].push({name, amount, price });
  return accumulator;
}, {});

This is a super useful example of reduce.

1

u/[deleted] Mar 24 '20

I'll have a look at this. Thanks

1

u/Macaframa Mar 24 '20

Yep. Just step through the logic and console log if you have to along the way to understand what is going on. Then try to manipulate those data in other creative ways. Remember, as front end engineers, our job is to display data. Taking data from a backend and shaping it how we need it to display is apart of the job.