我会在javascript中找到对象数组的3个最大值。
这是我的对象数组:
data = [
{"name" : "Ariana" , "score" : "130"},
{"name" : "Iggy" , "score" : "270"},
{"name" : "Aron" , "score" : "30"},
{"name" : "Josh" , "score" : "20"},
{"name" : "Kevin" , "score" : "10"},
{"name" : "John" , "score" : "80"},
{"name" : "Nicky" , "score" : "45"}]
我搜索的数组:
dataTop3 = [
{"name" : "Ariana" , "score" : "130"},
{"name" : "Iggy" , "score" : "270"},
{"name" : "John" , "score" : "80"}]
我只是设法用这段代码找到了更大的一个:
function value_max(data){
var max=0;
for (i in data) if(data[i]>max) max=data[i];
return max;
}
max=value_max(data);
答案 0 :(得分:1)
在您的解决方案中,您将根据条件替换每次迭代中的max值,最终只给出一个值,您需要使用一个数组来返回多个值。
解决方案是对整个数组进行排序,使用比较器函数比较每个对象中的得分键,然后根据需要使用前k个值。
var data = [
{"name" : "Ariana" , "score" : "130"},
{"name" : "Iggy" , "score" : "270"},
{"name" : "Aron" , "score" : "30"},
{"name" : "Josh" , "score" : "20"},
{"name" : "Kevin" , "score" : "10"},
{"name" : "John" , "score" : "80"},
{"name" : "Nicky" , "score" : "45"}];
data.sort((x,y) => y.score-x.score);
console.log(data.splice(0,3));
另一种解决方案是维护一个大小为4的数组,并在每次迭代时对其进行排序,并在最后一个位置添加下一个元素。
var data = [
{"name" : "Ariana" , "score" : "130"},
{"name" : "Iggy" , "score" : "270"},
{"name" : "Aron" , "score" : "30"},
{"name" : "Josh" , "score" : "20"},
{"name" : "Kevin" , "score" : "10"},
{"name" : "John" , "score" : "80"},
{"name" : "Nicky" , "score" : "45"}];
function value_max(data){
var max=0, vals = [];
for (i in data) {
if(vals.length === 4){
vals.sort((x,y) => y.score-x.score);
vals[3] = data[i]
}else{
vals.push(data[i]);
}
}
vals.sort().pop();
return vals;
}
max=value_max(data);
console.log(max);
答案 1 :(得分:1)
您可以对数组的副本进行排序并对顶部项进行切片。
var data = [{ name: "Ariana", score: "130" }, { name: "Iggy", score: "270" }, { name: "Aron", score: "30" }, { name: "Josh", score: "20" }, { name: "Kevin", score: "10" }, { name: "John", score: "80" }, { name: "Nicky", score: "45" }],
top3 = data
.slice()
.sort(function (a, b) { return b.score - a.score; })
.slice(0, 3);
console.log(top3);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)
如果我正确理解了您的问题,您可以先使用以下排序函数根据得分对数组进行排序:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
然后,您可以轻松获得第一个或最后三个项目,具体取决于您排名第一或最低的第一项。所以如果你排在第一位:
sortedArray[0], sortedArray[1], sortedArray[2]
答案 3 :(得分:0)
你尝试过这样的事吗?
while ( data.length > 3) {
if (data[3] > data[2]) {
data.splice(2,1);
} else if (data[3] > data[1]) {
data.splice(1,1);
} else if (data[3] > data[0]) {
data.splice(0,1);
} else {
data.splice(3,1);
}
}
dataTop3 = data;