Manilavie
Manilavie

Reputation: 125

Get the index of the largest value of an array of objects

I have an object table in which there is the score and the name of a character and I would like to retrieve the index with the highest score to be able to make a scoreboard.

This is what my array looks like

[
    {
        "score": 51,
        "name": "toto"
    },
    {
        "score": 94,
        "name": "tata"
    },
    {
        "score": 27,
        "name": "titi"
    },
    {
        "score": 100,
        "name": "tutu"
    }
]

In this case, I would like to get the index of the person who has the highest score, in this case, the index is 3 because it is tutu who has the highest score.

Thank advance for ur help

Upvotes: 0

Views: 65

Answers (5)

George Lioris
George Lioris

Reputation: 11

[...].reduce((acc, item, idx) =>  (item.score > acc.score ? {score: item.score, index: idx} : acc), {score: 0, index:0}).index

Upvotes: 0

Nonik
Nonik

Reputation: 655

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

Upvotes: 1

Sunny
Sunny

Reputation: 4809

Using for loop

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);

Upvotes: 1

zinen
zinen

Reputation: 78

The sort function should do it:

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

More info at w3schools

Upvotes: 2

ug_
ug_

Reputation: 11440

You can use the reduce function

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

Upvotes: 1

Related Questions