0

With a list of objects like this:

var products = [
  {productName: "Soap", qty: 2}, 
  {productName: "Shampoo", qty: 3}, 
  {productName: "Spray", qty: 1}
];

What would be the most efficient method to return the object in this list with the highest qty? (e.g. an alternative to use a for loop)

If there are two objects with the same qty, it would be ok to just return the first object with the highest qty in the list.

3 Answers 3

4

You should use sort and then retrive the element.

products.sort(function(a,b){
     return b.qty - a.qty
})[0]
Sign up to request clarification or add additional context in comments.

Comments

3

You could use Array#reduce and get the first one with the highest quantity.

This solution needs only one iteration: O(n).

var products = [{ productName: "Soap", qty: 2 }, { productName: "Shampoo", qty: 3 }, { productName: "Spray", qty: 1 }],
    highest = products.reduce(function (r, a, i) {
        return !i || a.qty > r.qty ? a : r;
    }, undefined);

console.log(highest);

Comments

1

I think the best way of doing it would be sorting and then retrieving element. Because sort is optimized on engine level and would be most efficient. I think, 95% of times, It'll use MergeSort.

product.sort(function(a, b) {
    return a.qty - b.qty 
})

This will sort elements in qty ascending order.

See Array.prototype.sort docs at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

2 Comments

It will require n^2 comparisons. It's less effective then for loop and reduce. But it definitely less cryptic (at least for me).
Yeah, now I see, it might be a very naive approach.

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.