我有一个posts
的列表。这些帖子有一个日期(created
)和一个分数(score
)。我想做的是按created
和score
对它们进行排序,但将score
作为更重要的变量。
换句话说,按照created
的顺序对所有帖子进行排序,但显示最高的score
首先显示。.
从本质上说:
score: 6, created: july 1 //created is actually a timestamp 1530372915676
score: 4, created: july 1
score: 2, created: july 1
score: 1, created: july 1
score: 5, created: june 30
score: 3, created: june 30
我找到了这段代码:
array.sort(function (x, y) { return x.created - y.created || x.score - y.score; });
但它似乎不起作用。
做到这一点的最佳方法是什么?
答案 0 :(得分:2)
这可以满足您的要求。它将首先按created
的顺序按descending
进行排序,并且在每个created
项中,它将按score
的{{1}}进行排序。类似于sql查询descending(highest score first)
order by created desc, score desc
编辑:
这也应该工作,无需使用arr.sort(function (x, y) {
if(x.created != y.created)
{
return y.created - x.created
}
else return y.score-x.score
});
if
答案 1 :(得分:0)
只需在分数比较中交换x
和y
。在创建日期相同的情况下,它将使分数更高:
array.sort(function (x, y) { return x.created - y.created || y.score - x.score; });