Advertisement
elena1234

How to sort by two criteria - JavaScript

Aug 19th, 2021 (edited)
517
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // another example: Object.keys(register).sort((a, b) => Object.keys(register[b]).length - Object.keys(register[a]).length ||
  2. // a.localeCompare(b));
  3.  
  4. function solve(array) {
  5.    array.sort((a, b) => {
  6.     if(a.length  > b.length) { // first criteria
  7.         return 1;
  8.     } else if(a.length === b.length) {
  9.         return a.toLowerCase().localeCompare(b.toLowerCase()); // second criteria
  10.     } else {
  11.         return -1;
  12.     }  
  13.    })
  14.      
  15.     return(array.join('\n'));
  16. }
  17.  
  18. solve(['test',
  19. 'Deny',
  20. 'omen',
  21. 'Default']
  22. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement