The best way to approach this is to think about how you would solve it as a human.
As a human, you could sort a list of numbers, then a list of letters and combine the two results into one list.
Then you try to translate that into code.
As mentioned, try to focus on a working solution then think about refactoring.
@JeremyLT and @jwilkins.oboe , thank you so much for the quick responses!
I apologize for my late reply, but I really appreciate your advice!
Your advice harkens back to good 'ol CS fundamentals which I should not forget-- break things down into smaller problems!
This code seemed to work for me, although it may not be super elegant!
// problem: Sort this array:
let myarr1 = [1, 'ss', 11, 2, 'aa'];
// expected output:
// [ 1, 2, 11, 'aa', 'ss' ]
// extra test cases if you need them:
//let myarr2 = ['zzz', 1, 's', 11, 2, 'a', 111];
// solution:
function compareNumbers(a, b) {
//console.log('a: ' + a);
//console.log('b: ' + b);
//console.log('-------');
if (typeof a === 'number' && typeof b === 'number') {
return a - b;
}
// check for num vs string
if (typeof a === 'number' && typeof b === 'string') {
return -1;
}
// check for string vs num
if (typeof a === 'string' && typeof b === 'number') {
return 1;
}
// check for string vs string
if (typeof a === 'string' && typeof b === 'string') {
if (a < b) return -1;
else return 1;
}
return 0;
}
myarr1.sort(compareNumbers);
console.log(myarr1);
Again, thanks everyone for your help! I appreciate you greatly!
@Montin the return statements are following the guidelines of a custom compare function.
function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
See this site for complete info on how how to write your own comparison function:
Array.sort() uses a default comparison function, but if it doesn’t work the way you like, you can write your own comparison function as we did here, and pass the custom comparison function as a parameter to Array.sort().