我正在尝试找到选择具有最高特定属性值的对象(在这种情况下,错误答案的数量)并返回另一个属性(名称)的最佳方法。例如。以下对象应返回Mark:
[
{name: "Henry", age: "NYN", attempts: 3, wrong: 2},
{name: "Mark", age: "NNNY", attempts: 4, wrong: 3},
{name: "Beth", age: "", attempts: 0, wrong: 0},
{name: "Sally", age: "YYNY", attempts: 4, wrong: 1},
]
最好的解决方法是什么(在JavaScript中)?谢谢你的帮助!
答案 0 :(得分:1)
这是一个简单的方法:
var objArray=[
{name: "Henry", age: "NYN", attempts: 3, wrong: 2},
{name: "Mark", age: "NNNY", attempts: 4, wrong: 3},
{name: "Beth", age: "", attempts: 0, wrong: 0},
{name: "Sally", age: "YYNY", attempts: 4, wrong: 1},
];
function getNameOfMostWrong(){
//Set first object in array for most wrong as default
var mostWrongPerson=objArray[0];
for(var person in objArray){
if(objArray[person].wrong > mostWrongPerson.wrong){
mostWrongPerson=objArray[person];
}
}
return mostWrongPerson.name;
}
答案 1 :(得分:1)
您可以使用简单的for循环来检查最高wrong
值并选择该对象。这将具有O(n)
的复杂度,类似于线性搜索算法。
var arr = [
{name: "Henry", age: "NYN", attempts: 3, wrong: 2},
{name: "Mark", age: "NNNY", attempts: 4, wrong: 3},
{name: "Beth", age: "", attempts: 0, wrong: 0},
{name: "Sally", age: "YYNY", attempts: 4, wrong: 1},
];
var highest = arr[0].wrong, index;
for(var i=1; i<arr.length; i++){
if(arr[i].wrong > highest){
highest = arr[i];
index = i;
}
}
var highestWrong = arr[index];
console.log('highest wrong attempt is done by', highestWrong.name);
&#13;