Javascript reduce function on array of objects
Array.reduce()
function in javascript is one of the most interesting functions,
but it may be tricky if you haven’t worked with it on an array of objects.
Let us first look at the following code (array of plain integers), the code basically sums up all the elements in the array:
[1, 2, 3].reduce((accumulator, element) => {
return accumulator + element;
});
The first thing to keep in mind is the arguments in the callback function,
The accumulator is a variable that collects the returned value on each iteration, and the element is the element we are on in the current iteration. The first iteration takes the first and the second element, the first element as accumulator and the second as an element so there is array.length – 1 iterations.
so, the iteration looks like this for the above code.
— iteration 1
accumulator: 1
element: 2
— iteration 2
accumulator: 3
element: 3
so the end result is 6.
That was straightforward. It becomes tricky with an array of objects though. What how would you do the sum of scores in the following array of objects.
[
{ subject: 'Maths', score: 10 },
{ subject: 'Chemistry', score: 7 },
{ subject: 'Physics', score: 8 },
];
The trick is that it is possible to add initial value to the accumulator which is when the first iteration set that value to the accumulator and iterates through each element once.
[1, 2, 3].reduce((accumulator, element) => {
return accumulator + element;
}, 4);
Here the accumulator starts as 4 and on each iteration, the corresponding element is added to it.
— iteration 1
accumulator: 4
element: 1
— iteration 2
accumulator: 5
element: 2
— iteration 3
accumulator: 7
element: 3
So the end result is 10.
I hope you already know what to do with that array of objects.
But anyway here is the answer:
[
{ subject: 'Maths', score: 10 },
{ subject: 'Chemistry', score: 7 },
{ subject: 'Physics', score: 8 },
].reduce((accumulator, element) => {
return accumulator + element.score;
}, 0);
The iterations look like this
— iteration 1
accumulator: 0
element: {subject: "Maths", score: 10}
— iteration 2
accumulator: 10
element: {subject: "Chemistry", score: 7}
— iteration 3
accumulator: 17
element: {subject: "Physics", score: 8}
So the sum of scores at the end is 25.
I have recently created a video on common JavaScript Array methods