Search code examples
javascriptarraysstringecmascript-6numbers

Sort an array which contains number and strings


I am trying to sort an array which contains strings, numbers, and numbers as strings (ex. '1','2'). I want to sort this array so that the sorted array contains numbers first and then strings that contain a number and then finally strings.

var arr = [9,5,'2','ab','3',-1 ] // to be sorted
arr.sort()
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
//arr = [-1, "2", 5, 9, "ab"] // actual result

I have also tried

var number =[];
var char =[];
arr.forEach(a=>{
 if(typeof a == 'number') number.push(a);
 else char.push(a);
})
arr = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
//  arr = [-1, 5, 9, "2", "ab", "3"]// actual result

Solution

  • It seems you have done most of the work in your second attempt. All I have done here is used Array.concat to join the sorted results of number and char together.

    var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
    var number = [];
    var char = [];
    arr.forEach(a => {
      if (typeof a == 'number') number.push(a);
      else char.push(a);
    })
    
    
    var sorted = number.sort().concat(char.sort());
    console.log(sorted)