Introduction
reduce() is a very import method in JavaScript, it executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
Here is the syntax of reduce() method:
1 | reduce(callbackFn) |
Most of the time, reduce() is used to sum up the values in an array, but it can be used for many other things as well.
1 | const nums = [1, 2, 3]; |
Why we use a and c for the parameters of the reducer function, because a = accumulator, c = currentValue.
Each call to the reducer produces a new value, and this value is passed to the next call of the reducer as the accumulator(first argument). Otherwise, a will become undefined in the next call.
Note that you must return value from the callbackFn, otherwise the result will be undefined.
1 | const nums = [1, 2, 3]; |
I found this when I working on the following work, group the following inventory by type property:
1 | const inventory = [ |
The output should look like this:
1 | { |
I write the following code, but got and error: TypeError: Cannot read properties of undefined (reading 'fruit'), do you know why?
1 | function groupByType(inventory) { |
I forgot the return a inside the callback function, so the a will be undefined in the next call, and undefined doesn’t have the property fruit.
To fix it, add return a at the end of the callback function.