获取对象数组中最大值的索引

我有一个对象表,其中有分数和角色名称,我想检索分数最高的索引以便能够制作记分板。


这就是我的数组的样子


[

    {

        "score": 51,

        "name": "toto"

    },

    {

        "score": 94,

        "name": "tata"

    },

    {

        "score": 27,

        "name": "titi"

    },

    {

        "score": 100,

        "name": "tutu"

    }

]

在这种情况下,我想获得得分最高的人的索引,在这种情况下,指数是3,因为得分最高的是tutu。


预先感谢您的帮助


开满天机
浏览 138回答 4
4回答

哆啦的时光机

该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})

回首忆惘然

使用for循环var index = 0;var max = 0;for (var i = 0; i < scores.length; i++) {&nbsp; if (s[i].score > max) {&nbsp; &nbsp; max = s[i].score;&nbsp; &nbsp; index = i;&nbsp; }}console.log(index);

汪汪一只猫

您可以使用该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;});

萧十郎

var data = [{&nbsp; &nbsp; "score": 51,&nbsp; &nbsp; "name": "toto"&nbsp; },&nbsp; {&nbsp; &nbsp; "score": 94,&nbsp; &nbsp; "name": "tata"&nbsp; },&nbsp; {&nbsp; &nbsp; "score": 27,&nbsp; &nbsp; "name": "titi"&nbsp; },&nbsp; {&nbsp; &nbsp; "score": 100,&nbsp; &nbsp; "name": "tutu"x&nbsp; }];var max_score = Math.max.apply(Math, data.map(function(o) {&nbsp; return o.score;}))console.log(data.filter(i => i.score === max_score))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript