You can use array.sort where you searchb the index of the space from the string and take for the comparison the original-string just from one position after the space.
Remark: For implementing the sort-function you have pay attention that there are 3 different return values for (a,b):
- Return:
< 0 => a<b
- Return:
= 0 => a=b
- Return:
< 0 => a>b
The result is now ok after I consider this (I had made here a mistake which is now corrected):
"id#2 XX car house", "id-3 abc home", "id1 abc test"
Note: XX stands before abc because uppercases are smaller than lowercases e.g. ASCII from "A" is 65 and from "a" is 97.
console.log('A'.charCodeAt(0));
console.log('a'.charCodeAt(0));
Here is the code-sample in extended version because it's not 100% clearified if for sorting the upper/lowercase-problematic is to be considered or not. So I added an extra parameter, so that now both variants are possible:
let arr = ["id1 abc test", "id#2 XX car house", "id-3 abc home"];
function specialSort(ignoreUpperCase) {
arr.sort( (a,b) => {
if (ignoreUpperCase) {
a = a.toUpperCase();
b = b.toUpperCase()
}
a = a.substr(a.indexOf(' ')+1);
b= b.substr(b.indexOf(' ')+1);
return (a<b) ? -1 : (a>b) ? 1 : 0;
});
}
specialSort(true);
console.log('Ignore UpperCases:',arr);
specialSort(false);
console.log('With UpperCases:',arr);
id1 abc testis beforeid-3 abc home?id-3 abc homeshould be before