Finally, without any fiery surprises, we can mix our tasty fruit pieces together into a grand fruit salad. The .reduce
method is great for this, since it allows us to loop through all of our chopped fruits and
add them into the bowl one by one until we end up with one, finished and mixed bowl.
Let's have a look at that.
const mix = (fruits, bowl = '') =>
fruits.reduce(
(content, fruit) => content + fruit.type
, bowl)
/*
This yields a String `🍎🍌🍈🍉🍊🍓` because
we're just concatinating these guys together.
*/
const fruitSalad = mix(fruitsWithoutChilis)
// But is it really a fruit salad? Let's check...
console.log(fruitSalad === `🍎🍌🍈🍉🍊🍓` ? '🥗' : '😱')
// 🥗, yay!
We did it! With a little help from .reduce
we could mix all our fruit pieces into one bowl. So, what happened here?
.reduce
is a very interesting method that can do tons of complex stuff, which is out of scope for this piece, but the gist of is that you "take multiple values and calculate them into one final value".
A typical use case is summing up stuff, like counting how many fruit pieces there were in total. The uses are endless when you start to really get a grasp of it.
One gotcha is the initial value that you can pass a .reduce
method. In our case we pass an empty bowl String
, but it can basically be anything. A number, an Array, an Object, etc.
The initial value can be a bit strange at first, but in our fruit salad example you can try and think of it as the empty bowl itself. It is "connected" to the content
variable, so whenever we do an operation, we're looking
into the bowl and adding more stuff to it's current content.
Until we don't have anything left, that is. Then .reduce
stops and returns the final result.