Skip to content

Instantly share code, notes, and snippets.

@brauliodiez
Last active June 4, 2018 10:01
Show Gist options
  • Save brauliodiez/7c320ac0da4d748a1977cd7acc3b490c to your computer and use it in GitHub Desktop.
Save brauliodiez/7c320ac0da4d748a1977cd7acc3b490c to your computer and use it in GitHub Desktop.
Simple ES6 reduce sample

reduce

Reduce allows us calculate a total, applying an operation on every operation of an array.

This can save us lot of "for" loops (enhannce readibility).

steps

Let's implement a function that will sum up an array.

Usually we would do something like:

const sales = [20, 30 ,25];


function totalSales(sales) {
  let totalSales = 0;

  for(let i=0;i< sales.length;i++) {
    totalSales += sales[i];
  }
  
  return totalSales;
}

console.log(totalSales(sales));

By Using reduce:

const sales = [20, 30 ,25];

function totalSales(sales) {
  return sales.reduce((total, sale) => total += sale)
}

console.log(totalSales(sales));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment