Here is an array of objects that I'm working with:
const data = [
{
"order_id":38795,
"order_type":"Music",
"date":"2021-08-14",
"name":"Concert",
"tickets":[
{
"id":9,
"ticket_type":"Priority",
"quantity":2,
"price":25,
"detail":{
"Adults":1,
"Children":0,
}
},
{
"id":10,
"ticket_type":"Priority",
"quantity":1,
"price":10,
"detail":{
"Adults":0,
"Children":1,
}
},
{
"id":10,
"ticket_type":"Standard",
"quantity":3,
"price":15,
"detail":{
"Adults":1,
"Children":0,
}
}
]
},
{
"order_id":84874,
"order_type":"Film",
"date":"2021-08-14",
"name":"Adventure",
"tickets":[
{
"id":7,
"ticket_type":"Standard",
"quantity":1,
"price":20,
"detail":{
"Adults":1,
"Children":0,
}
}
]
}
];
I am looking to calculate the total quantity of Adult tickets for orders with the 'Music' order type.
In this scenario, the answer would be 5 (2 * Adult Priority and 3 * Adult Standard)
To begin, I have used the filter
method on the array to extract only the 'Music' order_type
const musicOrders = data.filter((order) => {
return order.order_type == 'Music'
});
When it comes to summing up the quantities, I believe using the reduce
method will iterate through the quantity values.
.reduce((total, ticket) => {
return total + ticket.quantity;
}, 0)
However, I am unsure how to combine filtering by both
order_type = "Music"
ticket.detail.Adults = 1 / true
And retrieving the quantities in a single function. Any suggestions?