The most confusing array method

The most confusing array method

Reduce() is not just another array method; it's more than that. Do you think I'm exaggerating? No, I'm not. Keep reading below to find out why.

This array method requires two arguments:

  1. Callback function

    • This callback function is invoked with the following arguments:
      i. accumulator
      ii. currentValue
      iii. currentIndex
      iv. array (The array on which reduce() was called)
  2. InitialValue (optional)

Example:

const arr = [1,2,3,4]; // array of numbers

function callBackFunc(accumulator, currentValue) { // callback function for reduce
    return accumulator + currentValue; // this returned value will become accumulator for the next iteration
}

const initialValue = 0; // default value

const sum = arr.reduce(callBackFunc, initialValue);

console.log(sum); // printing the sum of all array values

// Output: 10

Explanation:

  • In the above example, we are displaying the sum of all the array values.

  • We set initialValue = 0 because if no initialValue is provided, reduce() will use the first value in the array, leading to incorrect calculations.

  • In the callback function, whatever we return becomes the accumulator value for the next iteration. This is the power of reduce(); we can obtain the result of the previous returned value.

  • Using the reduce() method, we can perform various operations such as aggregation and segregation.

In essence, the reduce() method goes beyond just being another array function. It provides developers with a powerful tool for concise and elegant data manipulation in JavaScript. By allowing the aggregation, transformation, and segregation of array elements using a customizable callback function that works on an accumulator, reduce() makes complex operations clear and efficient.