Given a list of device models, let’s say iPhone models and names, I want to create a javascript sorting function that will return them in order. Currently the list could look something like this:
list = ['iPhone 8 Plus', 'iPhone 8', 'iPhone 7 Plus', 'iPhone 7', 'iPhone 6S Plus', 'iPhone 6 16GB', 'iPhone 6', 'iPhone 13', 'iPhone 12 Pro Max', 'iPhone 12 Pro', 'iPhone 11']
Trying to do a normal sort function returns the order where 11, 12 and 13 are not correctly placed. I am guessing this is because the “1” in 11,12 and 13 is lesser than the “7,8,9” and thus during comparison of strings is misplaced.
list.sort((a: string, b: string) => {
if (a < b) {
return 1;
}
if (a > b) {
return -1;
}
return 0;
})
How could I write a function that takes the number 11 instead of just the first “1” in it as the comparision?