简体   繁体   中英

Comparing object properties in an array

Have a set of objects stored in an array. If I want to compare an attribute like weight, how would I do it in the most effective way? Let's say i want the fruitbasket to be full when weight = 10.

var fruitBasket = []
function addFruit(fruit, weight) {
 return {
  fruit: fruit,
  weight: weight  
 }
}
fruitBasket.push(addFruit(apple, 2));
fruitBasket.push(addFruit(orange, 3));
fruitBasket.push(addFruit(watermelon, 5));
//etc...

You would need to maintain a sum of the weights in the fruitBasket array somewhere, and before you add you should check it against the added weight of an item. No need to worry too much about the individual weight of an added item via accessing through the array -> object, instead let your function handle it.

var totalWeight = 0,
    maxWeight = 10;

function addFruit(fruit, weight) {
  // Adds items to the fruit basket iff weight does not exceed maxWeight
  if((totalWeight + weight) <= maxWeight) {
    totalWeight += weight;
    return {
      fruit: fruit,
      weight: weight  
    }
  }
}

For the specific example you gave I would use Array.reduce method as below:

var weight =fruitBasket.reduce(function(a,b){return a.weight + b.weight})

Which would give you the overall weight. Reduce info ( https://www.w3schools.com/jsref/jsref_reduce.asp )

However, the answer might depend on what you mean as effective (ie efficient, best performance, most readable etc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM