Trevor Orr
Trevor Orr

Reputation: 947

jquery filter array of objects to find object property with highest value

Is there a way to use the filter function to find an object in an array of objects with a property of the object having the highest or lowest value in the array?

So if I have the follow:

var items = [
    {"id" : "1", "xpos":123, "ypos" : 321},
    {"id" : "2", "xpos":456, "ypos" : 654},
    {"id" : "3", "xpos":789, "ypos" : 987}
]

I was wondering if you could use the filter command to find the item with the highest or lower xpos or ypos?

Upvotes: 1

Views: 2260

Answers (3)

kayen
kayen

Reputation: 4868

This questions is old but just wanted to post another solution using an Array prototype:

Array.prototype.getItem = function ( key, lowest ) {
    return ( this.sort( function ( a, b ) { return ( lowest ? a[ key ] - b[key] : b[ key ] - a[key] ) } )[0] )
}

var items = [
    {"id" : "1", "xpos":123, "ypos" : 321},
    {"id" : "2", "xpos":456, "ypos" : 654},
    {"id" : "3", "xpos":789, "ypos" : 987}
];

item.getItem( 'xpos' ); // {"id" : "3", "xpos":789, "ypos" : 987}
item.getItem( 'xpos', true ); // {"id" : "1", "xpos":123, "ypos" : 321}

Hope this helps!

Upvotes: 0

Kolby
Kolby

Reputation: 2865

Here is my solution

http://jsfiddle.net/7GCu7/131/

var xpos = [];
var ypos = [];

var items = [
    {"id" : "1", "xpos":123, "ypos" : 321},
    {"id" : "2", "xpos":456, "ypos" : 654},
    {"id" : "3", "xpos":789, "ypos" : 987}
];


$.each(items, function(key, value){
    xpos.push(value.xpos);
    ypos.push(value.ypos);
});

console.log('heighest xpos:' + Math.max.apply(Math, xpos));
console.log('heighest ypos:' + Math.max.apply(Math, ypos));

Came up with a better solution. This will give you a variable containing the entire object, rather than just the number.

http://jsfiddle.net/7GCu7/132/

var xposObj = {"id":"0", "xpos":0, "ypos":0};
var yposObj = {"id":"0", "xpos":0, "ypos":0};

var items = [
    {"id" : "1", "xpos":123, "ypos" : 321},
    {"id" : "2", "xpos":456, "ypos" : 654},
    {"id" : "3", "xpos":789, "ypos" : 987}
];

$.each(items, function(key, value){
    if(value.xpos > xposObj.xpos) xposObj = value;
    if(value.ypos > yposObj.ypos) yposObj = value;
});

console.log(xposObj);
console.log(yposObj);

Upvotes: 1

Alfredo
Alfredo

Reputation: 171

I'm not sure if you can do it with jQuery but the following JavaScript works:

var items = [
    {"id" : "1", "xpos":123, "ypos" : 321},
    {"id" : "2", "xpos":456, "ypos" : 654},
    {"id" : "3", "xpos":789, "ypos" : 987}
]

var findMax = function(pos,object)
{
var max = 0;
for (var key in object) {
  if (object.hasOwnProperty(key)) {
    if(object[key][pos] > max)
    {
        max = object[key][pos];
    }
  }
}
return max;
}


console.log( findMax("xpos",items ));
console.log( findMax("ypos",items ));

Upvotes: 1

Related Questions