I have an array of objects (over 5000 entries) with Units Sold data from several countries. I am trying to take all similar countries, add the amounts, and then return a new array of objects with only one occurrence of each country and its total amount.
I think the code below is on the right track but I'm sure I'm taking the inefficient route and positive that it's flat out wrong. Im sure I need to apply the reduce() method and probably use something else besides forEach() but I'm not sure how.
Been on this for a few days now and would love/appreciate some help. Thanks!
const data = [
{
"Country" : "USA",
"Units Sold" : 1245.56
},
{
"Country" : "Spain",
"Units Sold" : 7843.50
},
{
"Country" : "USA",
"Units Sold" : 1435.99
},
{
"Country" : "Uruguay",
"Units Sold" : 594.20
},
]
let result = [];
data.forEach((block) => {
if (result.length === 0) {
result.push({
Country: block.Country,
"Units Sold": block["Units Sold"],
});
} else {
data.forEach((e) => {
if (e.Country === block.Country) {
console.log("add values");
e["Units Sold"] += block["Units Sold"];
console.log(e);
}
});
}
});
Desired outcome:
const newArray = [
{
"Country" : "USA",
"Units Sold" : 2681.55
},
{
"Country" : "Spain",
"Units Sold" : 7843.50
},
{
"Country" : "Uruguay",
"Units Sold" : 594.20
},
]