I have this array
bidsList = [
{
supplierName:'A',
awardedCapacity:5,
switcherStatus: true
},
{
supplierName:'B',
awardedCapacity:10,
switcherStatus: true,
},
{
supplierName:'A',
awardedCapacity:5,
switcherStatus: false,
},
{
supplierName:'A',
awardedCapacity:3,
switcherStatus: true,
},
{
supplierName:'B',
awardedCapacity:5,
switcherStatus: true,
},
{
supplierName:'C',
awardedCapacity:2,
switcherStatus: false,
},
i needed to have separete array where when i make the iteration throught this array i will calculate the total of all awardedCapacities where the supplier name is same
For example i should have array where i will have this output
let newArr = [
{
supplierName: 'A',
totalAwarded: 13,
},
{
supplierName:'B',
totalAwarded: 15,
},
{
supplierName:'C',
totalAwarded: 2,
}
]
The solution for this is:
let newArr = [];
bidsList.reduce(function(acc, val) {
if (!acc[val.supplierName]) {
acc[val.supplierName] = { supplierName: val.supplierName, awardedCapacity: 0 };
newArr.push(acc[val.supplierName])
}
acc[val.supplierName].awardedCapacity += val.awardedCapacity;
return acc;
}, {});
console.log(newArr);
but now i need to check also if the switcherStatus is setted to true only - if it is setted to false i should not calculate it's awardedCapacity and i should not push into the array if it is the only one object
so the output should be
let newArr = [
{
supplierName: 'A',
totalAwarded: 8,
},
{
supplierName:'B',
totalAwarded: 15,
},
]
C
IS excluded here because it is switcherStatus false, and A is 8 - because on object was with switcherStatus of false
i can't find a way to modify this reduce code here for that purpose.
Just add a condition in your reduce
function
var bidsList = [{ supplierName: 'A', awardedCapacity: 5, switcherStatus: true }, { supplierName: 'B', awardedCapacity: 10, switcherStatus: true, }, { supplierName: 'A', awardedCapacity: 5, switcherStatus: false, }, { supplierName: 'A', awardedCapacity: 3, switcherStatus: true, }, { supplierName: 'B', awardedCapacity: 5, switcherStatus: true, }, { supplierName: 'C', awardedCapacity: 2, switcherStatus: false, } ]; var result = bidsList.reduce((a, c) => { if (c.switcherStatus) { let supplier = a.find(e => e.supplierName == c.supplierName); if (supplier) supplier.totalAwarded += c.awardedCapacity; else a.push({ supplierName: c.supplierName, totalAwarded: c.awardedCapacity }); } return a; }, []); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.