Skip to content

Instantly share code, notes, and snippets.

@iandesj
Last active November 14, 2019 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iandesj/4a0b1b36671cd1dee806369bb08acf9e to your computer and use it in GitHub Desktop.
Save iandesj/4a0b1b36671cd1dee806369bb08acf9e to your computer and use it in GitHub Desktop.
Examples of reduce() vs for loop
const animals = [
{animal: 'zebra', count: 4}, {animal: 'tiger', count: 2},
{animal: 'lion', count: 3}, {animal: 'turtle', count: 9},
{animal: 'pig', count: 2},
];
console.log('reduce() example');
const count = animals.reduce((total, curr) => {
return total += curr.count;
}, 0);
console.log('count =', count, '\n');
console.log('for loop example');
let countAgain = 0;
for (let i=0; i < animals.length; i++) {
countAgain += animals[i].count;
}
console.log('countAgain =', countAgain);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment