What is the use of reduce in Javascript?
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
let a=[1,5,6,7,8];
let total=a.reduce((total,currentValue)=>total+currentValue)
console.log(total);//prints 27
In the above example, we are using reduce for sum of array.
What in case if you want to pass a value to accumulator?
reduce accepts two params function, param.
let a=[1,5,6,7,8];
let total=a.reduce(((total,currentValue)=>total+currentValue),20)
console.log(total);//prints 47
How to use reduce in react now?
import React, { Component } from 'react'
export default class App extends Component {
render() {
let a=[1,5,6,7,8];
let total=a.reduce(((total,currentValue)=>total+currentValue),20)
return (
<div>
Total sum is {total}
</div>
)
}
}
Top comments (0)