ScanSkill

reduce

The reduce() method is used to reduce the size of the array by combining it into a single unit.

Syntax

array.reduce((previousValue, nextValue) => {
  // statements with a return statement
}, initialValue)

The reduce() method is connected to the right side of the array by using . operator. It contains previousValue, and nextValue() as parameter. It also can take initialValue which is not mandatory, it takes the place of previousValue when the method is in its first iteration.

Example

const numbers = [1,2,3,4];
const total = numbers.reduce(
  (previousValue, nextValue) => previousValue + nextValue
)
console.log(total) // Prints: 10

The reduce() method reduces the array into a single unit. In the above example, we can see that the reduce() method added all the items present inside the array giving us the total, which is 10.