0

从下面的代码中,我得到了适当的输出,但我希望数据以排序形式出现,即最近的数据必须排在最前面。数据必须根据当前日期和'win_date'的差异按降序排序。我是node.js的新手。在PHP的早期我曾经使用函数array_multisort来做到这一点。有人可以建议在nodejs中做同样的事情吗?

var post=[];

var sql2 ="SELECT `post_id`, `user_id`, `post`, `votes_count`, `win_date` FROM `tb_winning_posts` WHERE  `group_id`=?";
 connection.query(sql2,[groupId],function(err, result) {

 });

for(var i=0;i<result.length;i++)
{
var timeDiff = getTimeDifference(result[i].win_date);   //returns diff of cur date & given   date in day,hour,min
post.push({"post_id":result[i].post_id,"post":result[i].post,"votes":result[i].votes_count,"date":timeDiff}); 

}
console.log(post); //getting the data in order as stored in database
4

1 回答 1

1

基于答案https://stackoverflow.com/a/8837511/1903116

post.sort(function(a, b){
    var keyA = a.date, keyB = b.date;
    if(keyA < keyB) return 1;
    if(keyA > keyB) return -1;
    return 0;
});
console.log (post);
于 2013-08-17T12:25:46.547 回答