If you are looking to sort strings in alphabetical order rather than numbers, here's a sample problem and its solution.
Example Problem: Array of arrays (finalArray) with first entry a folder path and second entry the file name; sort so that array is arranged by folder first, and within identical folders, by file name.
E.g. after sorting you expect:
[['folder1', 'abc.jpg'],
['folder1', 'xyz.jpg'],
['folder2', 'def.jpg'],
['folder2', 'pqr.jpg']]
Refer to Array.prototype.sort() - compareFunction
finalArray.sort((x: any, y: any): number => {
const folder1: string = x[0].toLowerCase();
const folder2: string = y[0].toLowerCase();
const file1: string = x[1].toLowerCase();
const file2: string = y[1].toLowerCase();
if (folder1 > folder2) {
return 1;
} else if (folder1 === folder2 && file1 > file2) {
return 1;
} else if (folder1 === folder2 && file1 === file2) {
return 0;
} else if (folder1 === folder2 && file1 < file2) {
return -1;
} else if (folder1 < folder2) {
return -1;
}
});
Keep in mind, "Z" comes before "a" (capitals first according to Unicode code point) which is why I have toLowerCase(). The problem the above implementation does not solve is that "10abc" will come before "9abc".