2014-06-23 25 views
1

有沒有辦法使用過濾器函數來找到對象數組中具有最高或最低值的對象的屬性中的對象?jQuery的過濾器對象數組,以找到具有最高值的對象屬性

所以,如果我有如下:

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

我在想,如果你可以使用過濾器命令來查找最高或更低XPOS或ypos項目嗎?

回答

1

這裏是我的解決方案

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

想出了一個更好的解。這會給你一個包含整個對象的變量,而不僅僅是數字。

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); 
+0

我覺得我喜歡這個版本,我的代碼已經通過項目循環並找到了最低/最高值。這似乎是一種更簡化的方法。 –

1

我不知道,如果你可以用jQuery做,但下面的JavaScript的工作原理:

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

這個問題是舊的,但只是想利用數組原型發佈另一種解決方案:

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} 

希望這有助於!

相關問題