7

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;
};
Community
  • 1
  • 1
Kassem
  • 8,116
  • 17
  • 75
  • 116
  • Give us a full code of what you have or a jsfiddle.net demo. – gdoron Jun 05 '12 at 12:30
  • Possible duplicate of [Find index of object in array with highest value in property](https://stackoverflow.com/questions/16509075/find-index-of-object-in-array-with-highest-value-in-property) – Heretic Monkey Oct 08 '19 at 15:20

5 Answers5

9

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/

VisioN
  • 143,310
  • 32
  • 282
  • 281
1
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)))]
)
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
0

Sort array and pop the last object in array

function sortObj(a, b){
     return a.order < b.order ? 0 : 1;
}
obj.sort(sortObj)   
var highest =obj.pop();

DEMO: http://jsfiddle.net/VaYNb/

charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

use yourarray.sort().it will sort in ascending to descending order.its valid for 2-D arrays also.

lovin
  • 563
  • 2
  • 14
  • 27
-1

try this:

function getHighest(array, value){
  return array.sort(function(a,b){ b[value] - a[value] })[0];
}
Sagiv Ofek
  • 25,190
  • 8
  • 60
  • 55
  • 1
    sort is expensive to find the max value. You are doing more operations than what is needed. – epascarello Jun 05 '12 at 12:48
  • Your sorting function isn't returning anything, and to get the highest value at index `0`, you'd need to do the less than comparison `<`, though subtraction would be better. `b[value] - a[value]` –  Jun 05 '12 at 13:03