I attempted the code snippet below.
var SeatWithCat = [{
"level": "Level II",
"price": 5,
"quantity": 1,
"seats": "B3"
}, {
"level": "Level II",
"price": 5,
"quantity": 1,
"seats": "B1"
}, {
"level": "Level I",
"price": 10,
"quantity": 1,
"seats": "A2"
}, {
"level": "Level III",
"price": 30,
"quantity": 1,
"seats": "C1"
}, {
"level": "Level III",
"price": 30,
"quantity": 1,
"seats": "C2"
}, {
"level": "Level V",
"price": 50,
"quantity": 1,
"seats": "E1"
}, {
"level": "Level II",
"price": 5,
"quantity": 1,
"seats": "B2"
}, {
"level": "Level VI",
"price": 2,
"quantity": 1,
"seats": "F1"
}];
var temp = [];
var jsonarr = [];
for (var i = 0; i < SeatWithCat.length; i++) {
for (var j = 1; j < SeatWithCat.length; j++) {
if (SeatWithCat[i].level === SeatWithCat[j].level) {
temp.push({
level: SeatWithCat[i].level,
quantity: SeatWithCat[i].quantity + SeatWithCat[j].quantity,
price: SeatWithCat[i].price + SeatWithCat[j].price,
seats: SeatWithCat[i].seats + "," + SeatWithCat[j].seats
});
SeatWithCat = SeatWithCat.filter(function(el) {
return el.level !== SeatWithCat[i].level;
});
jsonarr = SeatWithCat;
alert(JSON.stringify(temp));
}
}
}
var finalObj = temp.concat(jsonarr);
alert(JSON.stringify(finalObj));
Results:
[{
"level": "Level II",
"quantity": 2,
"price": 10,
"seats": "B3,B1"
}, {
"level": "Level III",
"quantity": 2,
"price": 60,
"seats": "C1,C1"
}, {
"level": "Level VI",
"quantity": 2,
"price": 4,
"seats": "F1,F1"
}, {
"level": "Level I",
"price": 10,
"quantity": 1,
"seats": "A2"
}, {
"level": "Level V",
"price": 50,
"quantity": 1,
"seats": "E1"
}]
The existing solution works fine when only two objects share the same level. However, it fails to calculate correctly when more than two objects in the array have the same level. My goal is to account for any number of objects with matching levels. Appreciate your help!