Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of object in array with highest value in property

I've got an array with objects:

var articles = [];
var article = {};

Simple loop that iterates x times {
        article.text = "foobar";
        article.color = "red";
        article.number = 5;
        articles.push(article);
}

I have no idea how many objects there will be in my array but they will all have different values for their properties, I just gave some examples here.

Question

I need to find a way to go through all these objects and retrieve the index of the object that has the highest value in article.number. How can I achieve this? I may only use javascript, jQuery, etc.. no other languages.

I'm guessing this will involve using both $.grep and Math.max but I'm stuck, I've never worked with $.grep before.

In short:

var highestNumber = index of object where article.number is highest
like image 848
Rijstkoek Avatar asked May 12 '13 15:05

Rijstkoek


2 Answers

There are many ways to do this, Math.max(), $.grep and $.map being a few, but an easy and readable method that should be understandable is to just iterate the object, and check if the value is higher than a variable, if it is, set the variable to the higher number :

var highest = 0;

$.each(articles, function(key, article) {

    if (article.number > highest) highest = article.number;

});

// highest now contains the highest number
like image 50
adeneo Avatar answered Oct 23 '22 18:10

adeneo


Underscore.js is a wonderful library that provides functional operations for collections. A solution in underscore:

var maxObj = _.max(array, function (obj) {
  return obj.number;
});
var maxIndex = array.indexOf(maxObj);

While this example is fairly simple, the operations scale nicely. Say you wanted to sum the number property for each object in the array that had text equal to Foo and color equal to red:

var customSum = _.chain(array)
  .where({ 
    text: "Foo", color: "red"
  })
  .map(function(obj) {
    return obj.number; 
  })
  .reduce(function(memo, num) {
    return memo + num;
  }, 0)
  .value();  

If you're at all concerned with performance, an external library is certainly the way to go. There are a huge amount of optimizations that external libraries can provide that would be difficult to match in your own code. That said, when dealing with a small number of items (less than several thousand) there won't be an appreciable performance difference between any of the answers posted here. Don't sweat the benchmarking and use the answer that's the most understandable to you.

JSFiddle

like image 27
ljfranklin Avatar answered Oct 23 '22 19:10

ljfranklin