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((a, b) => a - b); // If the data type of a given element is a number store it in this array (and then sort numerically)
const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort lexicographically)
const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]
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)