reduce() method:
The reduce() method executes a user-supplied reducer callback function on each of the array elements, and after calculating it returns a single value.
The first time that the reducer callback function is run no return value of the previous calculation. We can set an initial value as the second parameter of the reducer callback function for the previous calculation. Here, the second parameter is optional.
const arr = [23, 10, 49, 10];
const result = arr.reduce((acc, currVal) => {
return acc + currVal;
}, 0);
console.log(result);
// Result : 92
We can also set an object as an initial value.
let staffs = [
{ name: "Susan", age: 14, salary: 100 },
{ name: "Daniel", age: 16, salary: 120 },
{ name: "Bruno", age: 56, salary: 400 },
{ name: "Jacob", age: 15, salary: 110 },
{ name: "Sam", age: 64, salary: 500 },
{ name: "Dave", age: 56, salary: 380 },
{ name: "Neils", age: 65, salary: 540 }
];
const newSalary = staffs.reduce(
(total, currVal) => {
let singleTotal = currVal.salary;
total.initialSalary += singleTotal;
let discountVal = currVal.salary * 0.1;
total["initialDiscount"] += discountVal;
return total;
},
{ initialSalary: 0, initialDiscount: 0 }
);
console.log(newSalary);
Post a Comment