Sort an array which contains number and strings

  • A+
Category:Languages

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 

 


You can sort the integers first and then the non-integers by using .filter() to separate both data-types.

See working example below (read code comments for explanation):

const arr = [9,5,'2','ab','3',-1];  const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort) const non_nums = arr.filter(x => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums array (and then sort)  const res = [...nums, ...non_nums]; // combine the two arrays console.log(res); // [-1, 5, 9, "2", "3", "ab"]

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: