Reduce in JS
Lets make arrays great again!
As the name suggests, it reduces the array to 1 value (Depends on the business value). It takes a function and an initial value (if not given, it will take the first elements of array as the initial value).
Function is applied to each value in the array and the result is stored in the accumulator.
arr.reduce(fn, initialValue)
const fn = (accumulator, arrayElement) = {/* Business logic here */}
Eg:
let employees = [
{
name: "Abhinav",
salary: 200000
},
{
name: "Joey",
salary: 400000
},
{
name: "Chandler",
salary: 10000
}
]
Task: We want to sum the salary of all the employees. One way is to do the old way of using a for loop and the storing the value or we can use reduce which we just learnt now.
let salary = employees.reduce((accumulator, employee) => {
return accumulator + employee.salary;
}, 0)