Sort by 2 variables prioritizng 1
Sort by 2 variables prioritizng 1
I have a list of posts
. These posts have a date (created
) and a score (score
). What I would like to do is sort them by created
and score
but having score
as the more important variable..
posts
created
score
created
score
score
In other words sort all posts in order of created
but having the highest score
show first..
created
score
So essentially:
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
I found this piece of code:
array.sort(function (x, y) { return x.created - y.created || x.score - y.score; });
but it doesn't seem to work..
What would the best way of doing this be?
score
created
2 Answers
2
This could satisfy your requirement. It will first sort by created
in descending
order, and within each created
item, it will sort by score
in descending(highest score first)
. Similar to sql query order by created desc, score desc
created
descending
created
score
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
});
EDIT :
This should work too, without using if
if
arr.sort(function (x, y) { return y.created - x.created || y.score - x.score; });
Will the result be different from the original code?
– ConnorsFan
Jul 1 at 16:51
OP is showing the example of the result they want. So this should work.
– Amit Chigadani
Jul 1 at 16:55
It should now work, yes. Why use the
if
? You could keep the ||
operator.– ConnorsFan
Jul 1 at 17:01
if
||
Yes, that indeed works. Thanks!
– Amit Chigadani
Jul 1 at 17:07
Just swap x
and y
in the score comparison. It will make higher score go first in cases when the created date is the same:
x
y
array.sort(function (x, y) { return x.created - y.created || y.score - x.score; });
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
There seems to be a contradiction in your question. You say that
score
should be "the most important variable", but your example shows that the most important variable iscreated
. Is the example the result that you get with your current code, or the result that you want?– ConnorsFan
Jul 1 at 16:46