按2个变量排序,优先级为1

时间:2018-07-01 16:03:21

标签: javascript angular sorting

我有一个posts的列表。这些帖子有一个日期(created)和一个分数(score)。我想做的是按createdscore对它们进行排序,但将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; });

但它似乎不起作用。

做到这一点的最佳方法是什么?

2 个答案:

答案 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)

只需在分数比较中交换xy。在创建日期相同的情况下,它将使分数更高:

array.sort(function (x, y) { return x.created - y.created || y.score - x.score; });