I have this array
const a = ['s2', 'sb', 's5', 's1', 'sc', 's3', 's4']
After sort I want to this result:
['sb', 'sc', 's1', 's2', 's3', 's4', 's5']
I tried use sort() but didnt work
I have this array
const a = ['s2', 'sb', 's5', 's1', 'sc', 's3', 's4']
After sort I want to this result:
['sb', 'sc', 's1', 's2', 's3', 's4', 's5']
I tried use sort() but didnt work
use String.match
to get the chars after s
, if the chars are numbers use a-b
to sort else use localeCompare
.
const a = ["s2","sb","s5","s1","sc","s3","s4","s100","s10","sz","san"];
a.sort(
(a, b) => (a.match(/s(\d*)/)[1] - b.match(/s(\d*)/)[1]) || a.localeCompare(b)
);
console.log(a);
You can initially sort with localeCompare, and then by testing if number exists:
const a = ['s2', 'sb', 's5', 's1', 'sc', 's3', 's4', 's10', 'sa', 'sza', 's200', 's12', 's113'];
a.sort((a, b) => a.localeCompare(b, 'en', { numeric: true }))
.sort((x, y) => (/[0-9]/g).test(x) - (/[0-9]/g).test(y));
console.log(a);
// ["sa", "sb", "sc", "sza", "s1", "s2", "s3", "s4", "s5", "s10", "s12", "s113", "s200"]