What is array reduce() in Javascript?
In Javascript, array.reduce() is a higher-order function that takes in a function as an argument and and repeatedly applies a binary operation to the list of values to reduce the list of values in the array to a single value.
Prototype
Array.prototype.reduce(callbackfn, initialValue)
Parameters
-
callbackfn: The callback function that is executed on each of the values in the array.callbackfntakes in 4 additional arguments:accumulator: Theaccumulatorholds the accumulated result of applying thecallbackfnto the list.accumulatoris initialized withinitial Valueif an initial value is supplied.current value: The current value being processed in the array.index(optional): The index of the current value being processed.indexstarts from if theinitial Valueis provided; otherwise, it starts from .array(optional): The array on whichreduce()is called upon.
-
initalValue(optional):initialValueis used as the first value for thereduce()operation. If it is not supplied, then the first value at index is used as theaccumulator.
Return value
reduce() returns the accumulated result of applying the function on each of the elements in the array.
Code
const myNumbers = [-1, 9, -10, 4, 99]const sum = myNumbers.reduce((acc, curr) => acc + curr)console.log("Sum =", sum)const sumAllPositive = myNumbers.reduce((acc, curr, index) => {if (curr > 0){return acc + curr;}else{return acc;}}, 0)console.log("Sum of all positive elements =", sumAllPositive)
The code above demonstrates the use of the reduce function. Here, we use the reduce function to first calculate the sum of all the elements in the array. Then, we proceed to calculate the sum of only the positive integers in the array.
In the first case, we call reduce without supplying the initalValue. The reduce() function uses the first element as the accumulator value, sums up all the elements one by one, and returns the result.
In the second case, we need to supply the accumulator value because otherwise, the reduce() function will use the value at the index as the accumulator, which in this case is a negative value and should not be counted in the sum of all positive numbers.
Free Resources