ArticleZip > Sum All Data In Array Of Objects Into New Array Of Objects

Sum All Data In Array Of Objects Into New Array Of Objects

Working with arrays of objects in coding can be both challenging and exciting. One common task developers often face is the need to sum up specific data within an array of objects and then store this aggregated data in a new array of objects. In this article, we'll walk through how to achieve this in a simple and structured way.

Let's say you have an array of objects like this:

Javascript

const data = [
  { id: 1, value: 10 },
  { id: 2, value: 20 },
  { id: 3, value: 30 }
];

Your goal is to sum the `value` property of each object and then store the results in a new array of objects. To do this, we can use the `map()` function along with the `reduce()` function in JavaScript. Here's how you can accomplish this:

Javascript

const result = data.reduce((acc, obj) => {
  const index = acc.findIndex(item => item.id === obj.id);
  
  if (index >= 0) {
    acc[index].total += obj.value;
  } else {
    acc.push({ id: obj.id, total: obj.value });
  }

  return acc;
}, []);

console.log(result);

In the code snippet above:
- We use the `reduce()` function to iterate over the array and accumulate the sum for each unique `id`.
- Inside the reducer function, we check if the current object's `id` already exists in the accumulator array using `findIndex()`.
- If the `id` exists, we simply add the `value` to the existing `total`. If not, we push a new object with the `id` and `value` as the `total` into the accumulator array.
- Finally, we return the accumulator array with the sum of values for each unique `id`.

After executing the code, you will get a new array of objects that looks like this:

Javascript

[
  { id: 1, total: 10 },
  { id: 2, total: 20 },
  { id: 3, total: 30 }
]

By following this approach, you can efficiently sum up data in an array of objects and organize it into a new array based on your requirements. This method allows you to perform this task with ease and flexibility in your JavaScript projects.

I hope this step-by-step guide helps you understand how to sum all data in an array of objects into a new array of objects. Happy coding!