To sum the values of an array of objects with the same name, you will need to keep track of the running total for each name value. Here’s an example:
let items = [
{name: 'Item 1', price: 10},
{name: 'Item 2', price: 20},
{name: 'Item 1', price: 30},
{name: 'Item 3', price: 20},
{name: 'Item 2', price: 10},
{name: 'Item 1', price: 20}];
let totals = {};
for (let i = 0; i < items.length; i++) {
let name = items[i].name;
if (name in totals) {
totals[name] += items[i].price;
} else {
totals[name] = items[i].price;
}
}
console.log(totals); // Output: {Item 1: 60, Item 2: 30, Item 3: 20}
In this example, we start by initializing an empty object totals. We then loop through each object in the items array, and for each object, we check if its name value is already a key in the totals object. If it is, we add the object’s price value to the running total for that key. If it’s not, we create a new key in the totals object with the object’s name value as its key and the object’s price value as its value.
At the end of the loop, the totals object will contain a key-value pair for each unique name value in the items array, where the key is the name value and the value is the total sum of all objects with that name value.
You can also use the reduce method to accomplish the same result in a more concise way. Here’s an example:
let items = [
{name: 'Item 1', price: 10},
{name: 'Item 2', price: 20},
{name: 'Item 1', price: 30},
{name: 'Item 3', price: 20},
{name: 'Item 2', price: 10},
{name: 'Item 1', price: 20}
];
let totals = items.reduce((acc, item) => {
if (item.name in acc) {
acc[item.name] += item.price;
} else {
acc[item.name] = item.price;
}
return acc;
}, {});
console.log(totals); // Output: {Item 1: 60, Item 2: 30, Item 3: 20}
In this example, we use the reduce method to loop through each object in the items array and calculate the running total for each unique name value. The reduce method takes a function as its first argument, which is called for each element in the array. The second argument is the initial value of the accumulator, which is an empty object {} in this case.
The function takes two arguments: the accumulator object and the current object in the array. In the function, we check if the name value of the current object is already a key in the accumulator object. If it is, we add the price value of the current object to the running total for that key. If it’s not, we create a new key in the accumulator object with the name value of the current object as its key and the price value of the current object as its value.
At the end of the reduce method, the accumulator object will contain a key-value pair for each unique name value in the items array, where the key is the name value and the value is the total sum of all objects with that name value.