After successfully achieving the desired results, here is the data manipulation I have done:
const days = [
{
date: '2016-12-13T00:00:00.000Z',
stats: [
{ name: 'Soft Drinks', sold: 34, },
{ name: 'Snacks', sold: 3, },
{ name: 'Coffee and warm drinks', sold: 26, },
],
},
{
date: '2016-12-14T00:00:00.000Z',
stats: [
{ name: 'Soft Drinks', sold: 34, },
{ name: 'Snacks', sold: 3, },
{ name: 'Coffee and warm drinks', sold: 26, },
],
},
];
const newStats = days.reduce(function (pastDay, currentDay) {
const nextStats = currentDay.stats.map(function(stat) {
const oldSold = pastDay.stats.find(function (old) {
return old.name === stat.name;
});
const newSold = stat.sold + oldSold.sold;
stat.sold = newSold;
return stat;
});
return {
stats: nextStats,
};
});
console.log(newStats);
The output I obtained is:
{
"stats": [
{
"name": "Soft Drinks",
"sold": 68
},
{
"name": "Snacks",
"sold": 6
},
{
"name": "Coffee and warm drinks",
"sold": 52
}
]
}
While the initial structure worked perfectly, I encountered an issue when applying the same logic to a different array of objects. The error message "undefined error on pastDay
" is appearing. Can someone assist in identifying the problem or suggesting an alternative to the .reduce
method?
Below is the array causing the problem:
const days = [
{
"_id":{
"_str":"f23f02994ab992437e423e24"
},
"date":"2016-12-13T00:00:00.000Z",
"statistics":{
"breakdown":{
"byTurnover":[
{
"name":"Soft Drinks",
"sold":34,
"percentage":31.14
},
<snippet shortened for brevity>
],
}
},
"id":{
"_str":"f23f02994ab992437e423e24"
}
},
<snippet shortened for brevity>
{
"_id":{
"_str":"e1906ce07ab811c74528e3cc"
},
"date":"2016-12-15T00:00:00.000Z",
"statistics":{
"breakdown":{
"byTurnover":[
<snippet shortened for brevity>
],
}
},
"id":{
"_str":"e1906ce07ab811c74528e3cc"
}
},
];
const newStats = days.reduce(function (pastDay, currentDay) {
const nextStats = currentDay.statistics.breakdown.byTurnover.map(function(stat) {
const oldSold = pastDay.statistics.breakdown.byTurnover.find(function (old) {
return old.name === stat.name;
});
const newSold = stat.sold + oldSold.sold;
stat.sold = newSold;
return stat;
});
return {
stats: nextStats,
};
});
console.log(newStats);
Upon running the code for the second array, the following error was encountered:
Uncaught TypeError: Cannot read property 'breakdown' of undefined
Here is the .reduce code for the second array:
const newStats = days.reduce(function (pastDay, currentDay) {
const nextStats = currentDay.statistics.breakdown.byTurnover.map(function(stat) {
const oldSold = pastDay.statistics.breakdown.byTurnover.find(function (old) {
return old.name === stat.name;
});
const newSold = stat.sold + oldSold.sold;
stat.sold = newSold;
return stat;
});
return {
stats: nextStats,
};
});
console.log(newStats);