JavaScript Array reduce() Method

The JavaScript array reduce() method is used to reduce the elements of an array to a single value. It executes a provided function for each value of the array (from left-to-right). The return value of the function is stored in an accumulator (result/total).

Syntax:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Parameters:

function(total, currentValue, currentIndex, arr) – A function to execute on each element in the array.

Parameters of reducer’s function

totalRequired.
The initialValue, or the previously returned value of the function.
currentValueRequired.
The value of the current element.
currentIndexOptional.
The index of the current element.
arrOptional.
The array the current element belongs to.

Example

var arr = [1, 2, 3, 4, 5];

var sum = arr.reduce(function(a, b) {
    return a + b;
});

console.log(sum); // 15

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: