Skip to content

Instantly share code, notes, and snippets.

@juanpablocs
Last active September 9, 2020 05:19
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 juanpablocs/87484d3e8ae026ae4fd463fd39a1849d to your computer and use it in GitHub Desktop.
Save juanpablocs/87484d3e8ae026ae4fd463fd39a1849d to your computer and use it in GitHub Desktop.
Reduce js basic examples..

Simple

[1,2,3,4].reduce( (acc,current) => acc+current , 0); // result => 10

Object sum

[
  {item: 10},
  {item: 15}
].reduce( (acc, current) => {
  for(let k in current) {
    acc[k] = (acc[k] || 0) + current[k];
  };
  return acc;
 }, {}); // result => {item: 25}

Object sum and group

[
  {quantity: 10, item: 'a'},
  {quantity: 15, item: 'a'},
  {quantity: 25, item: 'b'}
].reduce( (acc, current) => {
  acc[current.item] = (acc[current.item] || 0) + current.quantity;
  return acc;
 }, {}); // result => {a: 25, b: 25}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment