I have an array of strings and I need to sort them first numerically if it contains a number and then if not sort alphanumerically.
Example:
const array = ["test 3","test 1","some test","another test","test 2"];
Expected result: test 1, test 2 , test 3, another test, some test
Preference for es6 solution.
You need to get a numerical value from the string or a large value to sort strings without any digit to the bottom. then sort by string.
const
getDigits = s => (s.match(/\d+/) || [Number.MAX_VALUE])[0],
array = ["test 3", "test 1", "some test", "another test", "test 2"];
array.sort((a, b) =>
getDigits(a) - getDigits(b) ||
a.localeCompare(b)
);
console.log(array);
const array = ["test 3","test 1","some test","another test","test 2"];
array.sort(function(a, b) {
let aNumber = a.replace( /^\D+/g, '');
let bNumber = b.replace( /^\D+/g, '');
if (aNumber.length * bNumber.length) {
a = parseInt(aNumber);
b = parseInt(bNumber);
} else if (aNumber.length + bNumber.length) {
return aNumber.length ? -1 : 1;
}
return ((a === b) ? 0 : ((a > b) ? 1 : -1));
})
console.log(array);
So, you have three main cases
You can use this function :
array.sort((a, b) => a.charCodeAt(a.length - 1) - b.charCodeAt(b.length - 1));