Using javascript sort()
method, I am trying to do sorting a list but sorting have in a group of even numbers and odd numbers.
The code which I tried is work
The short of the shortest:
n.sort(function(a, b) {
return a % 2 - b % 2 || a - b;
});
To make it work with negative numbers we can add Math.abs():
n.sort(function(a, b) {
return Math.abs(a % 2) - Math.abs(b % 2) || a - b;
});
Or even more compact variant using bitwise AND:
n.sort(function(a, b) {
return (a & 1) - (b & 1) || a - b;
});