Sort an array which contains number and strings Sort an array which contains number and strings arrays arrays

Sort an array which contains number and strings


The shortest is probably:

 arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));


You can sort the numbers first and then the non-numbers 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 => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)const res = [...nums, ...non_nums]; // combine the two arraysconsole.log(res); // [-1, 5, 9, "2", "3", "ab"]