I need to count the amount of times DishName appears in an array of objects, whilst also counting which are cooked and which are not, with the value of 1 being cooked and 0 being uncooked. So the following:
[{
"Cooked": 1,
"DishName": "85. Tikka Masala"
},
{
"Cooked": 0,
"DishName": "89. Lamb Rezalla"
},
{
"Cooked": 1,
"DishName": "85. King Prawn Masala"
},
{
"Cooked": 0,
"DishName": "85. Tikka Masala"
}]
Should return:
DishName -- Total Quantity -- Cooked -- Uncooked
This is a typical case for reduce. Reduce to an object that's keyed by the dish names. For each, record the total count and the counts of the other conditions (cooked / uncooked). Transform that result into an array of strings by mapping object entires.
let orders = [{
"Cooked": 1,
"DishName": "85. Tikka Masala"
},
{
"Cooked": 0,
"DishName": "89. Lamb Rezalla"
},
{
"Cooked": 1,
"DishName": "85. King Prawn Masala"
},
{
"Cooked": 0,
"DishName": "85. Tikka Masala"
}];
let summary = orders.reduce((acc, order) => {
if (!acc[order.DishName]) acc[order.DishName] = { count: 0, cooked: 0, uncooked: 0 };
acc[order.DishName].count++;
order.Cooked ? acc[order.DishName].cooked++ : acc[order.DishName].uncooked++;
return acc;
}, {});
// this produces:
// { "85. Tikka Masala" : { count: 2, cooked: 1, uncooked: 1 }}, ...
// formatted just like the OP...
let printReady = Object.entries(summary).map(([name, s]) => `${name} -- ${s.count} -- ${s.cooked} -- ${s.uncooked}`);
console.log(printReady);
const array = [{
"Cooked": 1,
"DishName": "85. Tikka Masala"
},
{
"Cooked": 0,
"DishName": "89. Lamb Rezalla"
},
{
"Cooked": 1,
"DishName": "85. King Prawn Masala"
},
{
"Cooked": 0,
"DishName": "85. Tikka Masala"
}];
const result = {};
array
.map(item => {
if (!result[item['DishName']]) {
result[item['DishName']] = {
quantity: 0,
cooked: 0,
uncooked: 0
}
}
result[item['DishName']].quantity++;
result[item['DishName']][item['Cooked'] ? 'cooked' : 'uncooked']++;
})
.sort((a, b) => a.quantity - b.quantity);
for ([key, value] of Object.entries(result)) {
console.log(`${key}--${value.quantity}--${value.cooked}--${value.uncooked}`);
}