useful array method in reduce()

useful array method in reduce()

·

2 min read

This is one of the most powerful methods introduced in javascript. If we want to talk about its use cases then we should write another blog just for its use cases, but still we look into the overview of reduce method.

The reduce method will run the callback function on every element of an array and the result(return) of the callback function will get assigned to previousValue. the final return of running reduce function will be a single value.

syntax

the reduce method will have 2 parameters where 1 is optional.

1) callback function which will run on every element of an array.

A callback function have 4 arguments previousValue(accumulator), currentValue(current), index, array.

prviousValue(accumulator) is the value of result from the previous callback function. But on the first call, this value will be initial value, If the initial value is not specified then this will be the value of array[0].

currentValue is the value of the current element. But on the first call, this will be the value of array[0] if the initial value is specified, otherwise it will be an array[1].

index is the index position of the current element. But on the first call, this will be index 0 if the initial value is specified, otherwise it will be 1.

#An array to traverse.

2) initial value is the value that is assigned to previousValue on the first call of callback function. If it is not specified then the previousValue will get initialized with array[0] value, Also current value will be array[1] and index will be 1.

// Arrow function
reduce((previousValue, currentValue) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ }, initialValue)

// Callback function
reduce(callbackFn)
reduce(callbackFn, initialValue)

// Inline callback function
reduce(function(previousValue, currentValue) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ }, initialValue)

since there are so many use cases we will look into a simple example.

example(sum of array elements):

const arr=[1,2,3,4,5,6,7,8,9]
const sum=arr.reduce((previousValue,currentValue)=>previousValue+currentValue,0)
console.log(sum)
//expected output:45

Notice here we are specifying the initial value to 0. So the previous value will be 0, and currentValue will be arr[1].

There are some edge cases in reduce method it will be good to know.Click here for the edge cases.

That's it folks

Did you find this article valuable?

Support ramu k by becoming a sponsor. Any amount is appreciated!