Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
array

What is array reduce() in Javascript?

Muhammad Ashir

In Javascript, array.reduce() is a higher-order function that takes in a function as an argument and and repeatedly applies a binary operation to the list of values to reduce the list of values in the array to a single value.

Prototype

Array.prototype.reduce(callbackfn, initialValue)

Parameters

  • callbackfn: The callback function that is executed on each of the values in the array. callbackfn takes in 4 additional arguments:

    • accumulator: The accumulator holds the accumulated result of applying the callbackfn to the list. accumulator is initialized with initial Value if an initial value is supplied.
    • current value: The current value being processed in the array.
    • index (optional): The index of the current value being processed. index starts from 00 if the initial Value is provided; otherwise, it starts from 11.
    • array (optional): The array on which reduce() is called upon.
  • initalValue (optional): initialValue is used as the first value for the reduce() operation. If it is not supplied, then the first value at index 00 is used as the accumulator.

Return value

reduce() returns the accumulated result of applying the function on each of the elements in the array.

Code

const myNumbers = [-1, 9, -10, 4, 99]

const sum = myNumbers.reduce((acc, curr) => acc + curr)
console.log("Sum =", sum)

const sumAllPositive = myNumbers.reduce((acc, curr, index) => {
  if (curr > 0){
    return acc + curr; 
  }
  else{
    return acc;
  }
}, 0)

console.log("Sum of all positive elements =", sumAllPositive)

The code above demonstrates the use of the reduce function. Here, we use the reduce function to first calculate the sum of all the elements in the array. Then, we proceed to calculate the sum of only the positive integers in the array.

In the first case, we call reduce without supplying the initalValue. The reduce() function uses the first element as the accumulator value, sums up all the elements one by one, and returns the result.

In the second case, we need to supply the accumulator value because otherwise, the reduce() function will use the value at the 00 index as the accumulator, which in this case is a negative value and should not be counted in the sum of all positive numbers.

RELATED TAGS

javascript
array

CONTRIBUTOR

Muhammad Ashir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring