How to use javascript reduce method?

In this article, let’s discuss the syntax and usage of the javascript reduce method.

The reduce() method executes a reducer function (user-defined) on each member (from left-to-right) of the array resulting in single output value. The accumulator stores the return value of the function. Javascript reduce method does not execute on an array without any elements.

Syntax

array.reduce(function(accumulator, currentValue, currentIndex, array), initialValue)
  • accumulatorRequired. The initial value, or the previously returned value of the function. This normally accumulates the callback value of the reduce method.
  • currentValue Required. The value of the current element
  • currentIndex Optional. The array index of the current element
  • Array – Optional. The array the reduce method was called upon
  • InitialValue – Optional. A value to be passed to the function as the initial value

Example

var numbersArray= [1, 2, 3, 4];

function sumAllNumbers(accumulator, currentNum) { 

  return accumulator + currentNum;

}

function mainFunction(item) {

 consolse.log('Sum of the numbers : ' || numbersArray.reduce(sumAllNumbers));

}

This is the syntax and usage guide of the javascript reduce method of javascript arrays.

See also:

Javascript remove element from array

Thanks for reading this tutorial. If you have any questions or improvements with respect to this tutorial, Please feel free the comment below or send me an email at [email protected]

Summary
javascript reduce method of javascript array
Article Name
javascript reduce method of javascript array
Description
This article explains how to use the javascript reduce method to accumulate javascript array values into a single value with syntax and examples.
Author
Publisher Name
askvikram.com
Publisher Logo

Leave a Comment