Javascript reduce method practical examples

Hi, in the last post we saw the definition about reduce method, etc. but in this post we are going to practice the reduce method and see how this method works in practical examples.

Sum an entire array Exercise:

// The array
const numbers = [10, 200, 90, 100, 100];

// Using the reduce method to get the sum of all numbers in the array
const sum = numbers.reduce((total, currentValue) => total +  currentValue);

// Printing sum
console.log('sum --->', sum);

Result:

If we need to initialized the total value with 5, we can do like this:

// The array
const numbers = [10, 200, 90, 100, 100];

// Using the reduce method to get the sum of all numbers in the array
const sum = numbers.reduce((total, currentValue) => {
    console.log('total-->', total);
    return total +  currentValue
}, 5);

// Printing sum
console.log('sum --->', sum);

Result:

Note: we can initialize the total (or accumulator) as an empty object too. 

array.reduce((acc, currentValue) => {
   return something
}, { })

Exercise Getting the total of years for all companies on the array of objects:

const companies = [
  {
    name: 'Company One',
    start: 1910,
    end: 2000
  },
  {
    name: 'Company One',
    start: 2000,
    end: 2020
  },
  {
    name: 'Company One',
    start: 1800,
    end: 2010
  }
];

const totalYears = companies.reduce((total, company) => {
  return total + (company.end - company.start);
}, 0);// we need to initialized the total because the first time will be the position one { }

console.log('totalYears --->', totalYears)

Result:

By Cristina Rojas