JS: Array.prototype.reduce
xArray.reduce(f, initValue)
-
- Recurse a function f of 2 parameters, let's call them state item.
- Each time,
- state is the last result of f.
- item is the new item in xArray.
- repeat untill no more items. Return the result.
- initValue is used for state when f starts.
💡 TIP: reduce aka fold, is a general purpose loop in functional programing style.
example
[1,2,3,4].reduce(f,0)
→f(f(f(f(0,1),2),3),4)
The function f is passed 4 args:
- The previous result
- The current array item
- The current array index (optional)
- The object being traversed (optional)
The function f should return one value.
const xx = ["1", "2", "3", "4"]; console.log(xx.reduce((x, y) => x + y, "0") === "01234");
xArray.reduce(f)
-
[1,2,3,4].reduce(f)
is same as
[2,3,4].reduce(f, 1)
example
[1,2,3,4].reduce(f)
→f(f(f(1,2),3),4)
- If array is empty, it's an error. Give initValue to avoid error.
- If array only has only one item, that item or the init value is returned.
const xx = [1, 2, 3, 4]; const f = ((x, y) => `f(${x},${y})`); console.log(xx.reduce(f) === "f(f(f(1,2),3),4)");
Example. Sum
// Sum of array console.log([1, 2, 3].reduce((x, y) => x + y) === 6);
Example. Empty Array, No Init Value
// empty array, no init value, is error [].reduce((x, y) => x + y); // error: Uncaught (in promise) TypeError: Reduce of empty array with no initial value
Example. Empty Array with Init Arg
// empty array, with init value. return init value console.log([].reduce((x, y) => x + y, 1) === 1);
Example. Array Just One Element, No Init Value
// array with just 1 element. no init value. return that element console.log( [1].reduce((x, y) => x + y) === 1, );