[英]Get the index of the largest value of an array of objects
我有一個對象表,其中有一個字符的分數和名稱,我想檢索具有最高分數的索引以便能夠制作記分板。
這就是我的陣列的樣子
[
{
"score": 51,
"name": "toto"
},
{
"score": 94,
"name": "tata"
},
{
"score": 27,
"name": "titi"
},
{
"score": 100,
"name": "tutu"
}
]
在這種情況下,我想獲得得分最高的人的指數,在這種情況下,指數為 3,因為得分最高的是 tutu。
感謝您的幫助
sort
函數應該這樣做:
var raw_scores = [
{
"score": 51,
"name": "toto"
},
{
"score": 94,
"name": "tata"
},
{
"score": 27,
"name": "titi"
},
{
"score": 100,
"name": "tutu"
}
]
var sorted_scores = raw_scores.sort(function(a,b){return b.score - a.score})
w3schools 上的更多信息
您可以使用reduce
功能
const array = [
{
"score": 51,
"name": "toto"
},
{
"score": 94,
"name": "tata"
},
{
"score": 27,
"name": "titi"
},
{
"score": 100,
"name": "tutu"
}
];
const highestScore = array.reduce((last, item) => {
// return the item if its score is greater than the highest score found.
if(!last || last.score < item.score) {
return item;
}
return last;
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
使用for
循環
var index = 0;
var max = 0;
for (var i = 0; i < scores.length; i++) {
if (s[i].score > max) {
max = s[i].score;
index = i;
}
}
console.log(index);
var data = [{
"score": 51,
"name": "toto"
},
{
"score": 94,
"name": "tata"
},
{
"score": 27,
"name": "titi"
},
{
"score": 100,
"name": "tutu"x
}
];
var max_score = Math.max.apply(Math, data.map(function(o) {
return o.score;
}))
console.log(data.filter(i => i.score === max_score))
[...].reduce((acc, item, idx) => (item.score > acc.score ? {score: item.score, index: idx} : acc), {score: 0, index:0}).index
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.