JavaScript Reduce method.

JavaScript Reduce method.

Reduce is a higher-order JavaScript function which executes reducer method provided to it on an array & unlike map or filter function it returns single value & not an array. Reduce takes the reducer function iterates over the array & performs reducer function for every array element.

Syntax-

array.reduce(reducerFun(acc, curr, currIndex, arr), initialValue)

  • array - It is the actual array on which reduce will be performed.

  • acc (required)- stores the return value from previous call of reducer function. initialised with initialValue provided to reduce along with reducer function

  • curr (required)- is the current element on array.

  • currIndex (optional)- is the index of curr element.

  • arr (optional)- is the actual array on which reduce is performed.

Examples-

Sum of elements in an array-

const arr = [1, 2, 3, 4, 5]
arr.reduce((acc, curr)=> {
    sum = acc + curr
    return sum
},0)

//15

As shown in above example function inside reduce will be performed for every array element the acc will be zero for first iteration as we have provided reduce with 0 initial value & then after every function call we are returning sum which is nothing but sum of old numbers & current number that is getting stored in acc.

Biggest no in an array

const arr = [1, 7, 3, 8, 4]
arr.reduce((acc, curr)=> curr > acc? curr : acc,0)

//8

In above example acc is initialised with 0 & every time acc is compared with curr value & if curr value is greater than acc it is getting stored at accumulator at the end we are getting greatest element in an array.

Age greater than 18

const arr = [
    {firstName: 'Narendra', LastName: 'Modi', Age: 16},
    {firstName: 'Joseph', LastName: 'Biden', Age: 28},
    {firstName: 'Vladimir', LastName: 'Putin', Age: 30},
    {firstName: 'Xi', LastName: 'Jinping', Age: 13},
    {firstName: 'Naftali', LastName: 'bennet', Age: 28}
]
arr.reduce((acc,curr) => {
    curr.Age > 18 ? acc.push(curr.firstName): null; 
    return acc
}, [])

//[ 'Joseph', 'Vladimir', 'Naftali' ]

In above reduce we have initialised acc with an empty array as shown & appending first names of the objects whose Age > 18. Hence, our final result have firstNames of objects having age greater than 18.

End Note: Thank You for reading. If you have any suggestion or query please feel free to comment below. Good Day! Happy Coding!!!