DEV Community

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

Collapse
 
kvsm profile image
Kevin Smith 🏴󠁧󠁢󠁳󠁣󠁴󠁿

If you have an array of things and what you want is a single thing, reduce is what you need.

It works by using a variable known as the 'accumulator', which is just the result you build up after processing each element in your array. In your case, that'd be ingredientString.

(I should point out at this point that your code as posted doesn't work - jsIngredients[i].value will always be undefined. Give the objects in your array consistent keys, like just ingredient instead of ingredient-1/2/3, then you can access them with jsIngredients[i].ingredient. I'll assume you made this change and carry on)

So, breaking down what reduce will do:

  • You pass reduce two things: a function (the 'reducer' function) which takes the 'accumulator' value and an element of your array, and an initial value for the accumulator
  • reduce will call your reducer function, passing it the initial accumulator value and the first element of your array
  • Your reducer function does whatever you like with the accumulator and your array element. It should eventually return a value, and that value will become the new value of the accumulator.
  • reduce then calls your reducer function again, passing the new accumulator value and the next element of your array.
  • Repeat until no more elements remain.

And in code:

const jsIngredients = [
    {"ingredient":"chicken"},
    {"ingredient":"brocolli"},
    {"ingredient":"cheese"}
]

let ingredientString = jsIngredients.reduce((acc, element) => {
    if (element.ingredient) {
        return acc + `${element.ingredient},`
    }
    return acc
}, '')

ingredientString = ingredientString.slice(0,ingredientString.length-1)
// "chicken,brocolli,cheese"

Note the passing of an empty string to reduce as the initial value. Also note this is a very rough idea of how reduce is typically used, see developer.mozilla.org/en-US/docs/W... for more details.

I also wrote goo.gl/9sQAQw but only ever got around to explaining map, still might be useful.

Finally, rather than writing the ingredient string manually and having to slice out the extra comma, consider how you might adapt this to use Array.prototype.join to solve this for you. 😁