Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript Array reduce()

The reduce() method iterates through each array element, applying a function to accumulate them into a single value.

It operates from left to right within the array. For its counterpart, see reduceRight().

The reduce() method does not alter the original array.

This example demonstrates finding the sum of all numbers within an array:

Example

const numbers = [45491625];
let sum = numbers.reduce(myFunction);

function myFunction(total, value, index, array) {
  return total + value;
}

It’s worth noting that the callback function accepts four arguments:

  • The total (initial value / previously returned value)
  • The item value
  • The item index
  • The array itself

In the provided example, since the index and array parameters are not utilized, they can be omitted:

Example

const numbers = [45491625];
let sum = numbers.reduce(myFunction);

function myFunction(total, value) {
  return total + value;
}

The reduce() method can optionally take an initial value.

Example

const numbers = [45491625];
let sum = numbers.reduce(myFunction, 100);

function myFunction(total, value) {
  return total + value;
}

JavaScript Array reduceRight()

The reduceRight() method iterates through each array element, applying a function to accumulate them into a single value.

It operates from right to left within the array. For its counterpart, see reduce().

The reduceRight() method does not alter the original array.

This example demonstrates finding the sum of all numbers within an array:

Example

const numbers = [45491625];
let sum = numbers.reduceRight(myFunction);

function myFunction(total, value, index, array) {
  return total + value;
}

Keep in mind that the function accepts four arguments:

  • The total (initial value or previously returned value)
  • The item value
  • The item index
  • The array itself

In the example provided, the index and array parameters are not utilized. Thus, it can be simplified as:

Example

const numbers = [45491625];
let sum = numbers.reduceRight(myFunction);

function myFunction(total, value) {
  return total + value;
}