How do I reduce an array in JavaScript?

The array.reduce(callback, initialValue) method in JavaScript is used to sequentially process each element of an array while storing the intermediate result. The reduce() method takes as its first argument a callback that is executed to run each element in the array; it applies in turn to each element of the array from left to right while maintaining the intermediate result. The second optional argument is the value that is used as the first argument of the first call to the callback function. If no argument is given, the first element of the array will be used. The reduce() method returns the value of the callback function, which is supplied as an argument the next time the function is called, causing the return value of the final call to evolve the return value of the method (the value is calculated from the elements of the array). In this JavaScript Reduce Array Example, we use the reduce() method to get the sum of the array elements. Click Execute to run the JavaScript Array Reduce Example online and see the result.
Loading...