Skip to content
Advertisement

Looping through and reducing nested array

I can’t seem to get my head around the array.reduce() function. I’ve got the following array:

JavaScript

and I’m trying to get a result like below. I’m not sure how to go about multiplying the ingredient amounts with the item quantities:

JavaScript

I’ve tried following the structure that was given here but the arrow function is throwing me off. Any sort of help would be greatly appreciated.

Advertisement

Answer

Read about reduce. It’s awesome. About this one, let me explain.

We start with this skeleton, preparing to group by some property:

JavaScript

That’s the idea!

Anyway, for each of these, we iterate the list of recipes and products, with the idea to collect instead of “some_property” the actual “ing_name”. While we group, we calculate the total. Finally, Object.values() will remove the keys we grouped by and turn it into the required array.

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement