Array reduce in javascript (minimal example)
Do you know for cycle? Yes?! Then you know javascript Array reduce method! Let’s say you have an array with numbers e.g. [1,1,1] and you want sum of them. Then you just loop over the array and in each cycle you add next value to intermediate result (current sum).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var array = [1, 1, 1]; | |
var current = 0; | |
var result; | |
for (var i=0, len=array.length; i<len;i++) { | |
current += array[i]; | |
} | |
result = current; | |
console.log(result); // logs 3 |
And that’s reduce, you just loop over the array and in each iteration you take next value and add/subtract/multiply or whatever you want with intermediate result.
Well and Array already knows how to reduce. It’s its prototype method (array.prototype.reduce)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var array = [1, 1, 1]; | |
var result; | |
result = array.reduce((current, next) => { | |
return current + next; | |
}) | |
console.log(result); // logs 3 |
So now you know how Array reduce function works. It’s only going from a list of values to one value.
You can now go to the Mozilla Docs for Array.prototype.reduce for a more in depth overview of javascript reduce method.