Skip to content

Instantly share code, notes, and snippets.

@juanpablocs
Last active Sep 9, 2020
Embed
What would you like to do?
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