How to sort an array so that null values always come last in Node.js

1 Answer

0 votes
function nullLast(ascending) {
  return function (a, b) {
    if (a === b) {
        return 0;
    }
    else if (a === null) {
        return 1;
    }
    else if (b === null) {
        return -1;
    }
    else if (ascending) {
        return a < b ? -1 : 1;
    }
    else { 
        return a < b ? 1 : -1;
    }
  };
}


const arr = ["php", "c++", null, "typescript", "c", null, "nodejs", null, "javascript", "python"]; 
 
arr.sort(nullLast(true));
console.log(arr);

arr.sort(nullLast(false));  
console.log(arr);

   
    
    
    
/*
run:
    
['c', 'c++', 'javascript', 'nodejs', 'php', 'python', 'typescript', null, null, null]
['typescript', 'python', 'php', 'nodejs', 'javascript', 'c++', 'c', null, null, null]
    
*/

 



answered Feb 26, 2022 by avibootz
...