JavaScript Array reduce() Method

You are Here:

JavaScript Array reduce() Method

The reduce() method executes a provided function on each element of the array, resulting in a single output value.

Note: This method does not alter the original array.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>Sum of Elements in myNumber is<p> <script> var myNumber = [1, 2, 3, 4, 5, 6, 7]; function sumUp(accumulator, currentValue, currentIndex, arr) { return num = accumulator + currentValue; } document.write(myNumber.reduce(sumUp)); </script> </body> </html>

Syntax

Array.reduce(function(accumulator, currentValue, currentIndex, arr), initialValue); //or Array.reduce(functionName);

Parameter Values

ValueTypeExplanation
function(accumulator, currentValue, currentIndex, arr)RequiredFunction to execute on each element in the array, taking four arguments.
accumulator - The accumulator accumulates the callback's return value i.e.) The initialValue, or the previously returned value of the function. Required.
currentValue - Specifies the current element being processed in the array. Required.
currentIndex - Specifies the index of the current element being processed in the array. Optional.
arr - Specifies the whole array. Optional.
initialValueOptionalSpecifies a value against which each element in an array is tested.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>Sum of Elements in myNumber is<p> <script> var myNumber = [1, 2, 3, 4, 5, 6, 7]; function sumUp(accumulator, currentValue, currentIndex, arr) { return num = accumulator + currentValue; } document.write(myNumber.reduce(sumUp, 100)); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author