hazeleyes
hazeleyes

Reputation: 11

JavaScript compare function not being called?

I have an object which contains an array. I am trying to sort the array by a win rate, but the following code doesn't seem to do anything at all. I can't see that the compareWinRate function is even getting called, but I am not sure why not.

let statistics = {
  wins: 0,
  kills: 0,
  deaths: 0,
  assists: 0,
  heroes: [],
};

statistics.heroes[hero1] = { matches: 5, wins: 2 };
statistics.heroes[hero2] = { matches: 5, wins: 4 };

function compareWinRate(a, b) {
  return ((b.wins / b.matches) - (a.wins / a.matches));
}

statistics.heroes.sort(compareWinRate);

If I display the array before and after the sort statement, they are the same.

Upvotes: 1

Views: 141

Answers (1)

גלעד ברקן
גלעד ברקן

Reputation: 23945

compareWinRate seems fine to me.

Just assign the stats objects to numeric indexes in the array:

statistics.heroes[0] = { matches: 5, wins: 2 };
statistics.heroes[1] = { matches: 5, wins: 4 };

Upvotes: 2

Related Questions