vannucci-dev
4/20/2020 - 2:39 PM

Reduce

The reduce() method reduces the array to a single value.

The reduce() method executes a provided function for each value of the array (from left-to-right).

The return value of the function is stored in an accumulator (result/total).

Note: reduce() does not execute the function for array elements without values.

Note: this method does not change the original array.

const array = [1, 2, 3, 4];

const reducedArray = array.reduce((accumulator, num)=>{
  return accumulator * num;
}), 1;
console.log(reducedArray); //24

const reducedArray = array.reduce((accumulator, num)=>{
  return accumulator + num;
}), 0;
console.log(reducedArray); //10

const reducedArray = array.reduce((accumulator, num)=>{
  return accumulator - num;
}), 2;
console.log(reducedArray); //-8