Skip to content Skip to sidebar Skip to footer

Sort Object Javascript

There are lots of questions similar to this but I couldn't find any quite like this. Here is my code. for (var i = 0; i < count_batters; i++) { var post = { player_name: j

Solution 1:

Push the objects into an array, then you can sort the array:

var posts = [];

for (var i = 0; i < count_batters; i++) {
  var post = {
    player_name: jsonData[i].player_name,
    fantasy_points: jsonData[i].avg_fpts_fd
  };
  posts.push(post);
}

function compare(a,b) {
  if (a.fantasy_points < b.fantasy_points)
    return -1;
  if (a.fantasy_points > b.fantasy_points)
    return1;
  return0;
}

posts.sort(compare);

Solution 2:

Looks like your compare function is inside of the for loop? If you take it out I imagine it would work. Or you could just put an anonymous function in sort as your compare function

post.sort(function(a,b) {
  if (a.fantasy_points < b.fantasy_points)
    return -1;
  if (a.fantasy_points > b.fantasy_points)
    return 1;
  return 0;
}

Post a Comment for "Sort Object Javascript"