Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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: jsonData[i].player_name,
    fantasy_points: jsonData[i].avg_fpts_fd
  }
  console.log(post);

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

  post.sort(compare);

I want to sort "post" by "fantasy_points". It is sorted by player_name by default. I have tried .sort() which doesn't work on this object. The error the above code gives is undefined is not a function

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
123 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)
    return 1;
  return 0;
}

posts.sort(compare);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...