0%

javascript-array-reduce

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
2
reduce(callbackFn)
reduce(callbackFn, initialValue)

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
2
3
const nums = [1, 2, 3];
const sum = nums.reduce((a, c) => a + c);
console.log(sum);

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
2
3
const nums = [1, 2, 3];
const sum = nums.reduce((a, c) => {a + c}); // won't work since we didn't return the value
console.log(sum); // undefined.

I found this when I working on the following work, group the following inventory by type property:

1
2
3
4
5
6
7
const inventory = [
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
{ name: 'bananas', type: 'fruit', quantity: 0 },
{ name: 'goat', type: 'meat', quantity: 23 },
{ name: 'cherries', type: 'fruit', quantity: 5 },
{ name: 'fish', type: 'meat', quantity: 22 },
];

The output should look like this:

1
2
3
4
5
6
7
8
9
10
11
{
vegetables: [ { name: 'asparagus', type: 'vegetables', quantity: 5 } ],
fruit: [
{ name: 'bananas', type: 'fruit', quantity: 0 },
{ name: 'cherries', type: 'fruit', quantity: 5 }
],
meat: [
{ name: 'goat', type: 'meat', quantity: 23 },
{ name: 'fish', type: 'meat', quantity: 22 }
]
}

I write the following code, but got and error: TypeError: Cannot read properties of undefined (reading 'fruit'), do you know why?

1
2
3
4
5
6
7
8
9
10
11
12
function groupByType(inventory) {
return inventory.reduce((a, c) => {
const type = c.type;
if (a[type]) {
a[type].push(c);
} else {
a[type] = [c];
}
}, {});
}
const result = groupByType(inventory);
console.log(result);

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.