JavaScript Array Reduce Method with Example

JavaScript Array Reduce Method with Example

javaScript array reduce method example; In this tutorial, you will learn everything about JavaScript Array reduce() method. And how to use this method with js arrays.

JavaScript Array reduce() method

First of all, you have a numeric array in javascript, like the following:

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

and you want to add each elements of an array.

So in that case, Iterate each element of an array and add them using for loop.

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

let total = 0;
for (let i = 0; i < numbers.length; i++) {
    total += numbers[i];
}
console.log(total);

Output:

15

How it works:

  • First of all, define an array in js script.
  • Next, define the total variable and assign it to zero.
  • Iterate for loop and add each elements of the numbers array and store in total variable.
  • Finally, console.log(); total variable.

Instead of for loop, you can use  reduce() method, that helps you to reduce an array to a single value.

See the following example:

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

let total = numbers.reduce(function (accumulator, current) {
    return accumulator + current;
});
console.log(total); // 15

Syntax of JavaScript Array reduce() method

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

arayObject.reduce(reducer [, initialValue])

Here,

Note that, The reduce() method calls the reducer() function for every element in the array.

1) The reducer function argument

The reducer() function has the following form:

function reducer(accumulator, currentValue, currentIndex, array){}

This function takes four arguments:

accumulator

The value returned from the previous call of the reducer function. If you pass the initialValue to the reduce() method,  when the reducer function is executed at the first time, the accumulator equals the initialValue.

currentValue

This is the current iteration value of an array element.

currentIndex

This is the current iteration index of an array element.

array

The array that the reduce() method was called upon.

The reducer() function executes on each element and returns a value. This return value is assigned to the accumulator argument in each iteration. At the final iteration, the value of the accumulator become the single resulting value.

2) The initialValue argument

The initialValue parameter is optional. If you pass in the initialValue parameter, the reduce() method will assign it to the previousValue parameter of the reducer() function at the first call of the reducer function.

The following table illustrates the logic when the reduce() method executes the reducer() function for the first time according to the initialValue argument.

initialValue accumulator currentValue
passed accumulator = initialValue currentValue = array[0]
not passed accumulator = array[0] currentValue = array[1]

Example : Array’s reduce() Method

Let’s take an example, you have one array of object and it contains array of the product with it’s some properties like, product, qty and price.

See the following:

let cartItem = [{
        product: 'phone',
        qty: 1,
        price: 699
    },
    {
        product: 'Screen Protector',
        qty: 1,
        price: 9.98
    },
    {
        product: 'Memory Card',
        qty: 2,
        price: 20.99
    }
];

And if you want to calculate the total amount of the products in the itemCart. So you can use the reduce() method.

See the following

let total = itemCart.reduce(function (acc, curr) {
    return acc + curr.qty * curr.price;
},0);

console.log(total);

Notice that in this example, we passed in the initialValue argument to the reduce() method.

Next, if you have a multiple arrays, and you want to concate in single array. You can done with javascript reduce() method.

See the following example:

let numbersArr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

let res = numbersArr.reduce((total, amount) => {
  return total.concat(amount);
}, []);


console.log(res); // // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Note that, Set the initial value to an empty array and then concatenate the current value to the total.

Conclusion

In this tutorial, you have learned how to use the JavaScript array reduce() with different examples.

Recommended JavaScript Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *