Reputation: 1150
I have an array [1, 85, -1, -1, 25, 0]
I need it sorted like this:
[0, 1, 25, 85, -1, -1]
Tried to use the sort() method but having no luck as its not in ASC order...
Logic: The values represent days from last order. -1
represents no order. Require it ordered by most recent ordered.
Upvotes: 0
Views: 82
Reputation: 4451
You could sort()
as usual and then explicitly move the -1
s to the end using splice()
and push()
.
let arr = [1, 85, -1, -1, 25, 0];
arr.sort((a, b) => a - b);
let idx = arr.findIndex(a => a != -1);
arr.push(...arr.splice(0, idx));
console.log(arr);
Upvotes: 1
Reputation: 1074008
In the sort
callback, you receive two arguments (I usually call them a
and b
). You return a negative number if a
should come before b
, 0 if it doesn't matter (they're the same for sorting purposes), or a positive number if a
should go after b
.
In your case, since -1 goes at the end (you've said there are no other negative numbers), you just need to special-case it:
array.sort((a, b) => {
if (a === -1) { // < 0 would also work, since there aren't any others
return 1;
}
if (b === -1) { // "
return -1;
}
return a- b;
});
Live Example:
const array = [1, 85, -1, -1, 25, 0];
array.sort((a, b) => {
if (a === -1) {
return 1;
}
if (b === -1) {
return -1;
}
return a- b;
});
console.log(array);
That can be more concise, of course, I wrote it as above primarily for maximum clarity. But for instance:
array.sort((a, b) => a === -1 ? 1 : b === -1 ? -1 : a - b);
Personally I prefer slightly more verbose than that. But... :-)
Upvotes: 3
Reputation: 386530
You could check if smaller than zero and sort the rest ascending.
var array = [1, 85, -1, -1, 25, 0];
array.sort((a, b) => (a < 0) - (b < 0) || a - b);
console.log(array);
Upvotes: 2