Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum of same objects with Array.reduce in Javascript

I have an array like this:

const inputArray = [
  {
    userId: 1,
    sum: 30,
  },
  {
    userId: 1,
    sum: 20,
  },
  {
    userId: 2,
    sum: 50,
  },
  {
    userId: 2,
    sum: 80,
  },
];

Then I wrote a function that sums the values ​​by key and got the following result:

const output = [
  {
    userId: 1,
    sum: 50,
  },
  50,
  {
    userId: 2,
    sum: 130,
  },
  130,
];

How can this error be corrected? Function code below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const output = inputArray.reduce((accumulator, currentItem) => {
  const index = accumulator.findIndex((item) => item.userId === currentItem.userId);

  if (index < 0) {
    return [...accumulator, currentItem];
  } else {
    return [...accumulator, (accumulator[index].sum += currentItem.sum)];
  }
}, []);

>Solution :

Try

const inputArray = [
  {
    userId: 1,
    sum: 30,
  },
  {
    userId: 1,
    sum: 20,
  },
  {
    userId: 2,
    sum: 50,
  },
  {
    userId: 2,
    sum: 80,
  },
];

const output = inputArray.reduce((accumulator, currentItem) => {
  const matchedItem = accumulator.find((item) => item.userId === currentItem.userId);

  if (!matchedItem) {
    return [...accumulator, currentItem];
  } else {
    matchedItem.sum += currentItem.sum
    return accumulator
  }
}, []);

console.log(output)

you were appending a new item to accumulator even when the item already existed, you just needed to mutate it. Also, since you dealing with an array of objects, you can use find as it will return a reference to the matched object itself, letting you update the object directly, rather than having to use findIndex then use the index to find it in the array again

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading