AppDividend
Latest Code Tutorials

Javascript Array Reduce Example | JS array.reduce()

1

Javascript array reduce() is an inbuilt method that executes the reducer function on each item of the array resulting in a single output value. The reduce() method reduces the array to a single value. The reduce() method executes the provided function for each value of the array (from left to right). The return value of the function is stored in the total.

Javascript Array Reduce Example

Javascript reduce() method does not execute a function for array items without values. The reduce() method reduces the array to a single value. Javascript array reduce() method executes a provided function for each value of the array (from left-to-right). The return value of the function is stored in an accumulator (result/total).

The syntax of the reduce() method is the following.

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

The total argument is required. It is the initial value or the previously returned value of the function.

CurrentValue is the required argument. It is the value of the current item in an array.

The currentIndex is an optional argument. It is the index of the current element.

The arr is an optional argument. It is the array object the current element belongs to.

The initialValue is an optional argument. It is a value to be passed to the function as the initial value.

The first time the callback is called total and currentValue can be one of two values. If an initialValue is provided in the call to the reduce() method, then the total will be equal to the initialValue, and currentValue will be equal to the first value in the array.

If no initialValue is provided, then the total will be equal to the first item in the array, and currentValue will be equal to the second.

Let us take an easy example of the array reduce() method in Javascript.

Create one file called app.js and write the following code inside the app.js file. We are using Node.js to run the file and display the output on the terminal.

// app.js

let arr = [1, 2, 3, 4, 5];
let sum = 0;
for(var i = 0; i < arr.length; i++) {
    sum += arr[i];
}
console.log(sum);

So, in the above example, we have used the for loop to sum all the items of the array. We can do the same thing using the javascript reduce() method.

// app.js

let arr = [1, 2, 3, 4, 5];

let sum = arr.reduce((x, y) => x + y);

console.log(sum);

Now run the file and output still will be 15.

Output

Javascript Array Reduce Example | Array.prototype.reduce() Tutorial

If the array is empty and it has no initialValue then, TypeError will be thrown. If an array has only one item (regardless of position) and no initialValue is provided, or if initialValue is provided, but an array is empty, then the single value will be returned without calling the callback function.

So, it performs like this.

[1, 2, 3, 4, 5].reduce(function(total, currentValue, currentIndex, array) {
  return total + currentValue;
});

The value returned by the reduce() would be that of the last callback invocation (15).

#Sum of values in an object array

Write the following code.

// app.js

let initialValue = 0;
let objArray = [
    {x: 1},
    {x: 2},
    {x: 3},
    {x: 4},
    {x: 5},
]
let sum = objArray.reduce(function (total, currentValue) {
    return total + currentValue.x;
}, initialValue);

console.log(sum);

So, in the above example, we have defined the initialValue to 0 and then pass the object values to the next, and then it will sum up all the values of all the objects and returns the output.

Output

Javascript reduce method tutorial with example

#Flatten an array of arrays in Javascript

We can use the reduce() method to flatten the array of arrays into one array with the individual items.

// app.js

let flattened = [[1, 2], [3, 4], [5, 6]]
    .reduce((total, currentValue) => total.concat(currentValue), []);

console.log(flattened);

Output

reduce method in javascript array

#Grouping Javascript objects by a property

Now in this example, we will group the object based on their age numbers. It is quite a difficult example at first, but after you understand it, it will become easy for you.

// app.js

const people = [
  { name: 'Krunal', age: 25 },
  { name: 'Rushikesh', age: 25 },
  { name: 'Ankit', age: 24 }
];

const groupBy = (objectArray, property) => {
    return objectArray.reduce(function (total, obj) {
        let key = obj[property];
        if (!total[key]) {
            total[key] = [];
        }
        total[key].push(obj);
        return total;
    }, {});
}

let groupedPeople = groupBy(people, 'age');

console.log(groupedPeople);

The above example will form an array of objects whose key is the age number and its properties are objects which have that same age number. So we are grouping the people based on their ages.

Output

Array Reduce method in Javascript

You can perform complex operations using the reduce() method. One of the most prominent examples is Redux. It uses the same pattern.

Finally, the Javascript array reduce() example is over.

1 Comment
  1. Amit Parmar says

    thanks for the post

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.