I need help sorting an array that contains various data types such as numbers, strings, and strings representing numbers (e.g. '1', '2'). The goal is to have all the numbers appear first in the sorted array, followed by strings containing numbers, and then standard strings.
var arr = [9, 5, '2', 'ab', '3', -1] // Array to be sorted
arr.sort()
// Expected result: [-1, 5, 9, "2", "3", "ab"]
// Actual result: [-1, "2", 5, 9, "ab"]
I attempted a different method:
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))
// Expected result: [-1, 5, 9, "2", "3", "ab"]
// Actual result: [-1, 5, 9, "2", "ab", "3"]