Sorting array by even and odd numbers

后端 未结 3 1965
闹比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;
    });
    
    0 讨论(0)
  • 2021-02-04 23:15

    My try:

    fiddle

    var n = [10,20,21,4,5,6,7,99,0,-12,12,13,-45,10,20,21,-13,4,5,6,7,99,0,12,13,10,-99,20,21,4,5,6,7,99,0,12,13,10,20,21,4,5,6,7,99,-15,-18,0,12,13];
    
    function sort(a, b) {
        if (!(a % 2) && !(b % 2)) {
            return a > b ? 1 : -1;
        }
        if ((a % 2) && (b % 2)) {
            return a > b ? 1 : -1;
        }
        if ((a % 2) && !(b % 2)) {
            return 1;
        }
        return -1;
    }
    console.log(n.sort(sort));​
    
    0 讨论(0)
  • 2021-02-04 23:32

    Change the code as follows:

    n.sort(function(a,b){
     if (a % 2 != b % 2 ){
       return a%2;
      }else {
          return (a - b) > 0 ? 1 : -1; 
      }
    });
    

    Working sample is here.

    Edit:

    n.sort(function(a,b){
     if (a % 2 != b % 2 ){
         return a%2 == 0 ? -1 : 1; // this is the fix :)
      }else {
          return (a - b) > 0 ? 1 : -1; 
      }
    });
    

    Edit 2: I've modifed the code for negative numbers. See working sample.

    n.sort(function(a,b){
     if (a % 2 != b % 2 ){
       return Math.abs(a)%2;
      }else {
          return a > b ? 1 : -1; 
      }
    });
    
    0 讨论(0)
提交回复
热议问题