Trevor Orr Trevor Orr - 6 months ago 101
Javascript Question

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?

Answer

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);
Comments