根据Object属性对JavaScript Object进行排序,但保留索引

时间:2013-11-06 17:43:06

标签: javascript

  

如果在JavaScript中出现这样的对象:

var data = [
            {"Person Name": "Amy", "Age":"46", "sex":"female"}
            {"Person Name": "John", "Age":"22", "sex":"male"}
            {"Person Name": "Mike", "Age":"62", "sex":"male"}
            {"Person Name": "Gav", "Age":"undefined", "sex":"male"}
           ]

并且想要找到最大年龄,但也想要返回索引值,即<2>

data[2]["Age"] 

在这个例子中,我该如何编码呢?我使用的数据对象包含1000多个条目,并且具有未定义的年龄值,因此需要进行搜索。

到目前为止我的解决方案是:

function maxIndex(/*string*/ property, /*array*/ searchArray){

    var maxIndex = 0;
    var maxValue = searchArray[0][property];

    for(i=1;i<searchArray.length;i++){

        if(searchArray[i][property] > maxValue){
            maxValue = searchArray[i][property];
            maxIndex = i;
        }
    }

   return maxIndex; 
}

呼叫:

maxAgeIndex = maxIndex("Age", data);

这似乎不起作用。我无法对“Age”属性中的数据对象进行排序,因为我丢失了索引号。

2 个答案:

答案 0 :(得分:1)

当数组元素小于到目前为止您看到的最大值时,您才更新最大值。这应该是一个大于测试:

  if (searchArray[i][property] > maxValue) {

另外,使用var声明“i”:

for (var i = 1; i < searchArray.length; i++) {

答案 1 :(得分:0)

如果您想使用功能方法,可以尝试这样的方法:

var ages = data.map(function(item){return parseInt(item.Age) || 0});
var maxAge = Math.max.apply(Math, ages);
var maxAgeIndex = ages.indexOf(maxAge);

|| 0表示'undefined'将变为0)


或者,正如Pointy建议的那样,你可以使用reduce:

var oldestPerson = data.reduce(function(memo, item){
   return parseInt(memo.Age) < parseInt(item.Age) ? item : memo
})