JavaScript Array Operations: Reduce

node v16.18.0
version: 1.0.0
endpointsharetweet
The reduce() method executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
/** * This reducer callback sums all the values in the array * * @param {any} previousValue - The value resulting from the previous call to the callback function. * On first call, initialValue if specified, otherwise the value of array[0]. * @param {any} currentValue - The value of the current element. * On first call, the value of array[0] if an initialValue was specified, otherwise the value of array[1]. * @param {number} currentIndex (Optional) - The index position of currentValue in the array. * On first call, 0 if initialValue was specified, otherwise 1. * @param {Array} array (Optional) - The array to traverse. */ function reducer (previousValue, currentValue, currentIndex, array) { /* return reducer operation result */ return previousValue + currentValue; }
// Let's start with an array of numbers const numbers = [1, 2, 3, 4, 5];
// Now we apply the reducer function to the array, calculating the sum of all numbers numbers.reduce(reducer);
// You can also pass an inline function, here we are calculating the multiplication of all numbers numbers.reduce((a, b) => a * b);
// Also, an initial value can be passed to the reduce method numbers.reduce((a, b) => a * b, 2);
Loading…

no comments

    sign in to comment