How to loop through the array of objects fruitsnveggies and compare them against the variable fruits and veggies to filter and sum up the values based on the arrays.
I want to create an array of object called totalproduce containing the sum of all quantities of fruits, veggies and others. I tried to loop through the variable fruitsnveggies using a forloop and used if/else conditions to appropriately match to the values from array called fruits, veggies and the leftover elements into others. The issue is I am not sure if I am doing it correctly or is there is a better way to do it.
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
}
}
Expected output should be as shown below
var totalproduce = [
{"items": "fruits", "quantity": 7},
{"items": "veggies", "quantity": 11},
{"items": "others", "quantity": 4}
]