3
89

JavaScript: How to use Array reduce() Method in JavaScript

Reading Time: 3 minutes

Array reduce() method is usually the go-to method if we need to iterate through to perform operation on every element using the return value from the previous iteration to produce 1 final value after completing all iteration. Array reduce() is introduced since ES5.

What is Array reduce Method

Array refers to standard built-in object in JavaScript and reduce() or Array.proto.reduce() method is part of Array as shown in the documentation. It is design to have a callback function execute over every element and return a final result based on all preceding iterations.

reduce() method takes in a callback function that have up to 3 argument inputs. 1st argument being the element data is compulsory where it is the element. 2nd argument is the index and 3rd argument is the original array where these are optional.

// Syntax of reduce() method
// passObject is optional, its purpose is for us to pass values in
myArray.reduce(callback[,passObject]);

// Syntax of callback function
function(previousValue, currentElement)
function(previousValue, currentElement, index)
function(previousValue, currentElement, index, originalArray)

There are 3 ways of how we can define the callback function. There are:

  • Arrow function
  • Callback function
  • Inline callback function

Let’s look at the illustration below. Since we do not need to pass data into the callback function, there is no need for passObject.

// Arrow Function Type
myArray.reduce((previousValue, currentElement) => { 
  return previousValue + currentElement;
});

// Callback Function Type
myArray.reduce(callbackFn);

// Inline Callback Function Type
myArray.reduce(function(previousValue, currentElement) { 
  return previousValue + currentElement;
});

Features of reduce()

  • Process on all elements and return the result to the next iteration.
  • Decide on what is the datatype of the return value.
  • Before the first execution of callback, it will capture and fix the array size to process.
    • Will not process new array elements.
  • If the array reference is changed in any iteration, the old array reference will still be used by the callback function for all iterations.
  • If a subsequent array element is updated in the earlier iteration, this new value will pass to the callback function when come to its iteration.
  • When no initial value, the callback function will execute from second element. First element will become the initial value.
  • When there is initial value, the callback function will execute from first element.

Usage of Array reduce() Method

Pre-ES5 Style

To write it via pre-ES5 style, we will need to create a boolean variable first, then if any of the element fail the validation, update boolean variable to false.

In the illustration below, we want to sum up all personArray age.

var personArray = [
  { name: 'Person1', age: 6 },
  { name: 'Person2', age: 30 },
  { name: 'Person3', age: 80 },
];

var totalAge = 0;
for (var i = 0; i < personArray.length; i++) {
  totalAge = totalAge + personArray[i].age;
}

console.log(totalAge);
// 116

ES5 Style

Let’s look into how to use reduce() method with the below example.

First, let’s define a basic array consisting of person and their age. Next, we want to sum up the age of everyone. We will just need to use the element here. No need index and original array data.

const personArray = [
  { name: 'Person1', age: 6 },
  { name: 'Person2', age: 30 },
  { name: 'Person3', age: 80 },
];

// We will pass in an initial value so that it will process from the first element
let initialValue = 0
let sumOfAge = personArray.reduce((previousValue, currentElement) => {
  return previousValue + currentElement.age;
}, initialValue);

console.log(sumOfAge);
// 116

Conclusion

From the above illustration, we can see that less code will be required if we use reduce() method instead of a traditional for-loop as we only need to take care of what to return to next iteration.

More Reading

Here are more articles on Array related methods.

Show Comments

No Responses Yet

Leave a Reply