首页 > 解决方案 > Find list of items(fruits) from an array in an array of object and calculate its quantity and push into another array as an object

问题描述

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}
]

标签: javascriptarraysjson

解决方案


试试这个代码jsfiddle以避免 long forEaches 和fors 等。使用filter,reduce你可以做强大的事情。在这里寻找方法Array

const fruits = ["apples", "oranges", "mango"]

const veggies = ["carrots", "onions", "brocoli"]

const 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}
];

const onlyVegies = fruitsnveggies
  .filter(a => veggies.includes(a.item))
  .reduce((acc, val) => {
    return {
      item: "veggies",
      quantity: acc.quantity + val.quantity,
    }
  }, {item: "veggies", quantity: 0});

const onlyFruits = fruitsnveggies
  .filter(a => fruits.includes(a.item))
  .reduce((acc, val) => {
    return {
        item: "fruits",
      quantity: acc.quantity + val.quantity,
    }
  }, {item: "fruits", quantity: 0});

  const others = fruitsnveggies
    .filter(a => !fruits.includes(a.item) && !veggies.includes(a.item))
    .reduce((acc, val) => {
      return {
        item: "others",
        quantity: acc.quantity + val.quantity,
      }
    }, {item: "others", quantity: 0});

  console.log("result: ", [onlyVegies, onlyFruits, others])

推荐阅读