How do I sort this array?
Input: ['sfr2ta', '2ab', 'bbb1ddd']
Output: ['bbb1ddd', 'sfr2ta', '2ab']
How do I sort this array?
Input: ['sfr2ta', '2ab', 'bbb1ddd']
Output: ['bbb1ddd', 'sfr2ta', '2ab']
If you want to sort it by the first charachter then the output should be like this: ['2ab', 'bbb1ddd', 'sfr2ta'].
But if you want to sort it that letters come before nubmers, then you write something like:
l = ['sfr2ta', '2ab', 'bbb1ddd'];
lNums = []
lStrs = []
for( let s of l ) {
if(s[0] >= 0 && s[0] <= 9){
lNums.push(s);
}
else {
lStrs.push(s);
}
}
lNums.sort();
lStrs.sort();
l = lStrs.concat(lNums);
console.log(l)
output: [ 'bbb1ddd', 'sfr2ta', '2ab' ]
Depending on how you want zero length strings to act (""), this should work:
function sortByFirstCharacter(arr) {
arr.sort((lhs, rhs) => {
if(lhs === rhs) return 0;
if(lhs === "") return -1;
if(rhs === "") return +1;
return (
lhs[0] < rhs[0] ? -1
: lhs[0] > rhs[0] ? +1
: 0
);
});
return arr;
}