Sorting array by even and odd numbers

后端 未结 3 1964
闹比i
闹比i 2021-02-04 23:03

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

3条回答
  •  再見小時候
    2021-02-04 23:10

    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;
    });
    

提交回复
热议问题