How to sort an array with null values in ascending order with Node.js

1 Answer

0 votes
const arr = ["php", "c++", null, "typescript", "c", null, "nodejs", null, "javascript", "python"]; 
 
arr.sort((a, b) => {
  if (a === null) {
        return 1;
  }
 
  if (b === null) {
        return -1;
  }
 
  if (a === b) {
        return 0;
  }
 
  return a < b ? -1 : 1;
});
    
console.log(arr);
   
    
    
   
    
/*
run:
    
['c', 'c++', 'javascript', 'nodejs', 'php', 'python', 'typescript', null, null, null]
    
*/

 



answered Feb 26, 2022 by avibootz

Related questions

...