How can I efficiently loop through the array of objects containing fruits and vegetables, compare them with predefined lists of fruits and vegetables, and then filter and sum up the quantities based on these arrays?
I am attempting to create a new array of objects named totalproduce, which should contain the total sum of quantities for fruits, vegetables, and any other items. My approach involves looping through the fruitsnveggies variable using a for loop, and applying if/else conditions to match the items with the predefined lists of fruits and vegetables. However, I am uncertain if my current method is the most effective way to achieve this goal.
var fruits = ["apples", "oranges", "mango"]
var veggies = ["carrots", "onions", "brocoli"]
var fruitsnveggies = [
{ "item": "apples", "quantity": 3},
{ "item": "oranges", "quantity": 2},
{ "item": "carrots", "quantity": 5},
{ "item": "mango", "quantity": 2},
{ "item": "brocoli", "quantity": 3},
{ "item": "chillipowder", "quantity": 3},
{ "item": "onions", "quantity": 3},
{ "item": "ketchup", "quantity": 1},
]
for(var i = 0; i < fruitsnveggies.length; i++){
if(fruitsnveggies[i]["item"] === fruits[i]){
//Code here
}else if(fruitsnveggies[i]["item"] === fruits[i]){
//Code here
}else{
//Code here
}
}
The expected output should be as follows:
var totalproduce = [
{"items": "fruits", "quantity": 7},
{"items": "veggies", "quantity": 11},
{"items": "others", "quantity": 4}
]