DEV Community

Discussion on: Explain it to me like I'm five: .map, .reduce, & .filter edition

Collapse
 
dmfay profile image
Dian Fay • Edited

Each of map, filter, and reduce steps through an array element by element and does something with each element, where 'something' is defined by the callback function you pass.

map applies a transformation to the element, so its callback function just takes the element itself (there are extra arguments, like the current index, in case you need them). So map's output is an array just as long as the original array, but where each element has been transformed from the original.

filter accumulates only those elements for which the callback function returns true. Like map, the callback operates on the original element with the same extra arguments, but it has to return a boolean-ish value. filter's output is an array which is either shorter or the same length as the original, and which contains only those elements for which the callback function returns a truthy value.

reduce works on a separate value which accumulates changes from each array element. Its callback is a little different: the first argument is the accumulator, then the element, then the extra arguments. It has to return the accumulator once it's been updated (or even if it hasn't -- filter + reduce is a waste of time, just use an if in the reduce callback!). You can use reduce to transform an array into something else entirely, like you're trying to do here.

There is a simple two-step solution involving map and join, but reduce will do it in one. I'll leave implementing the callback to you, but you're looking at const ingredientString = jsIngredients.reduce((accumulator, ingredient) => {...}, '');.

Also, doublecheck your original array -- based on your loop, the ingredient-x key should just be a consistent value instead.