What is reduce() method in JavaScript

What is reduce() method in JavaScript

ยท

2 min read

The reduce() method is used to apply a function to each element in the array to reduce the array to a single value.
Let's see the syntax:-

let result = array.reduce((acc, v, i, a) => {
  // return the new value to the result variable 
}, initVal);

// result - the single value that is returned. 
// array - the array to run the reduce function on. 
// acc - the accumulator accumulates all of the returned values. 
// v - the current value being processed
// i - the curret index of the value being processed
// a - the original array
// initVal - an optionally supplied initial value. 
// If the initial value is not supplied,
// the 0th element is used as the initial value.

The reduce() method can be thought of like a for loop, that is specifically for using the values of an array to create something new. Take a look at this example.

var array = [11, 12, 13, 14];
var sum = 0;
for(var i = 0; i  < array.length; i++) {
      sum += array[i];
 }

  // sum = 50

The goal of the code above is to find the sum of all of the values in our array. Yes, it works, but there is an easier way to archive the same result.

Rewriting the previous function using the reduce() method.

let array = [11, 12, 13, 14];
let sum = array.reduce((bcc, v) => bcc + v); 
    // sum = 50

Just see. Without any loop.

We've used the variable bcc to represent our accumulator. As our reduce function works through the array, the bcc value will increase until the function has completed.


Needy Extras.

Remember when I specified that we can use an optional initial value? It's pretty easy to set that up. We'll use the same example as above. We're going to sum our array, but this time, we want to start with an initial value of 250.

So how does it look when we start with an initial value of 250? Just see the example below and you'll get to know.

let array = [11, 12, 13, 14]; 
let sum = array.reduce((bcc, v) => bcc + v, 250);

As you can see, the code above is almost identical to the previous example. All that's changed is we've added a second argument after our callback. I've passed in the number 250 as our starting point. Now, when we run the function, the sum will equal 300.


Read more;-


Thanks For Reading ๐Ÿ˜

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!