I\'m looking for the easiest way to sort an array that consists of numbers and text, and a combination of these.
E.g.
\'123asd\'
\'19asd\'
\'12345asd\'
Imagine an 8 digit padding function that transforms:
We can used the padded strings to help us sort '19asd' to appear before '123asd'.
Use the regular expression /\d+/g to help find all the numbers that need to be padded:
str.replace(/\d+/g, pad)
The following demonstrates sorting using this technique:
var list = [
'123asd',
'19asd',
'12345asd',
'asd123',
'asd12'
];
function pad(n) { return ("00000000" + n).substr(-8); }
function natural_expand(a) { return a.replace(/\d+/g, pad) };
function natural_compare(a, b) {
return natural_expand(a).localeCompare(natural_expand(b));
}
console.log(list.map(natural_expand).sort()); // intermediate values
console.log(list.sort(natural_compare)); // result
The intermediate results show what the natural_expand() routine does and gives you an understanding of how the subsequent natural_compare routine will work:
[
"00000019asd",
"00000123asd",
"00012345asd",
"asd00000012",
"asd00000123"
]
Outputs:
[
"19asd",
"123asd",
"12345asd",
"asd12",
"asd123"
]