I'm working on a project where i am trying to get array with all 50 US states. I have some data where the id is the abbreviated version of the state and some where the id is the name of the state. I want all of the data to be under an id that is equal to the name of the state.
For this, I have:
let Array9 = (orderLocationUS);
Array9.forEach((state) => {
if (state._id === 'NY' || state._id === 'New York' || state._id === 'ny' || state._id === 'N.Y.' ){
state._id = 'New York'
}})
console.log(orderLocationUS)
console.log(orderLocationUS) gives:
[
{ _id: 'New York', count: 1, totalSales: 108.75 },
{ _id: 'New Jersey', count: 1, totalSales: 100 },
{ _id: 'New York', count: 31, totalSales: 627.93 }
]
I want the result:
[
{ _id: 'New Jersey', count: 1, totalSales: 100 },
{ _id: 'New York', count: 32, totalSales: 736.68 }
]
I tried to get the count by:
array10 = = orderLocationUS.filter((state) => state._id === 'New York').map(x => x.count).reduce((a, b) => a + b, 0)
console.log(array10)
This does give me 32, but I need this in an array format and I know this is probably not the right way to get the results I need. I would really appreciate suggestion on how to get the:
[
{ _id: 'New Jersey', count: 1, totalSales: 100 },
{ _id: 'New York', count: 32, totalSales: 736.68 }
]
array that I need.
Use includes to check if existing then just add if already present.
function combine() {
let array = [{
_id: 'New York',
count: 1,
totalSales: 108.75
},
{
_id: 'New Jersey',
count: 1,
totalSales: 100
},
{
_id: 'New York',
count: 31,
totalSales: 627.93
}
];
let output = [];
array.forEach(function(item) {
let existing = output.filter(function(v, i) {
return v._id == item._id;
});
if (existing.length) {
let existingIndex = output.indexOf(existing[0]);
output[existingIndex].totalSales += item.totalSales;
output[existingIndex].count += item.count;
} else
output.push(item);
});
console.log(output);
}
combine();