I've been trying to get my head around this but I've had no luck at all. I've tried various ways, one of it being the forEach
array method but I'm not able to get the output I need.
Idea is, MEAL DEAL: $2.99 - must be a combination of 1x Sandwich, 1x drink and 1x quick bite.
If it's just 1x each of the items in array, it works but when there are more than 1 of each item in array, I cant get it to work
I have the following array but it may vary:
[
{ "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
{ "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
{ "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
{ "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
{ "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]
I need to split that into parts like below:
IN MEAL DEAL
[
{ "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
{ "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
{ "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]
NOT IN MEAL DEAL (IF SANDWICH IS ADDED, IT BECOMES MEAL DEAL)
[
{ "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
{ "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 }
]
Sorry, if the explanation is not too good.
Idea is, each chunk must have all 3 element with following values. 1x COLD DRINK 1x SANDWICH 1x QUICK BITES
What I've tried:
var ITM ="";
var PER_CATEGORY_SET = [];
var value = [
{ "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
{ "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
{ "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
{ "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
{ "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 },
{ "CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5 }
]
value.forEach(function (my_item){
var xx = value.length;
while (xx > 0) {
if(ITM != my_item.CAT ){
ITM = my_item.CAT;PER_CATEGORY_SET.push({'CAT':my_item.CAT,'QTY':my_item.QTY,'PRICE':my_item.PRICE});
value.splice(0, 1);
}
xx--;
}
});
Output I get is below, it work to create only initial array than it don't do anything:
[
{ "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
{ "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
{ "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]