1

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...
1
  • Use Array.prototype.reduce with a function that adds the weight properties. Commented Oct 16, 2017 at 19:08

2 Answers 2

2

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  
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.