Javascript: reduce()

Prodip Sarker
1 min readAug 27, 2020

The reduce() method executes a reducer function on each element of the array.

### Syntax

arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])

### example

const numbers = [3, 5, 8, 9, 12];const total = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);console.log(total);
// 37

### To set a initialValue

const numbers = [3, 5, 8, 9, 12];
const result = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 3);
console.log(result);
// 40

### another one example for to set a initialValue

const numbers = [3, 5, 8, 9, 12];
const result = numbers.reduce((accumulator, currentValue) => accumulator - currentValue, 40);
console.log(result);
// 3

### here is details of every step changes value

const numbers = [3, 5, 8, 9, 12];
const result = numbers.reduce((accumulator, currentValue) => {
console.log(accumulator, currentValue);
return accumulator + currentValue;
}, 0);
console.log('Result: ', result);
// 0 3
// 3 5
// 8 8
// 16 9
// 25 12
// 25 12

### reduce method apply on a object of array

const employeeList = [
{
name: 'Piter',
salary: 1200
},
{
name: 'Harry',
salary: 1500
},
{
name: 'Mark',
salary: 1800
}
];
const totalSalary = employeeList.reduce((sum, employee) => sum + employee.salary, 0);console.log(totalSalary);
// 4500

--

--

Prodip Sarker
Prodip Sarker

Written by Prodip Sarker

in a relationship with console.log()

No responses yet