Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the element in the array with the max value of a property using jQuery

I have an array of a custom JavaScript object which has a property named order. I have an array of this object, and I want to get the item with the highest "order".

Since I'm relatively new to jQuery, and coming from a C# background this is one of the instances where I highly appreciate LINQ :)

Anyway, to cut a long story short, I've checked the following links but they only return the value and not a reference of the array element itself... So a little help in changing that to return the element would be appreciated.

jQuery min/max property from array of elements

element with the max height from a set of elements

The custom object in question(which I have an array of) is as follows:

var severity = function (key, value, order) {
    this.key = key;
    this.value = value;
    this.order = order;
};
like image 763
Kassem Avatar asked Jun 05 '12 12:06

Kassem


Video Answer


2 Answers

Maybe I got you wrong... but is that you are looking for?

function getHighest(array) {
    var max = {};
    for (var i = 0; i < array.length; i++) {
        if (array[i].order > (max.order || 0))
            max = array[i];
    }
    return max;
}

// var array = [object, object, object ...];
var highest = getHighest(array);

DEMO: http://jsfiddle.net/c6gfj/

like image 189
VisioN Avatar answered Sep 30 '22 14:09

VisioN


array[array.map((o)=>o.order).indexOf(Math.max(...array.map((o)=>o.order)))]

DEMO :

let array=[{order:3},{order:5},{order:2},{order:2}];

console.log(
  array[array.map((o)=>o.order).indexOf(Math.max(...array.map((o)=>o.order)))]
)
like image 38
Abdennour TOUMI Avatar answered Sep 30 '22 12:09

Abdennour TOUMI