The other issue is that we would have to sort based on the reference. Actually, it would be running the toString method on each of those and using those to sort. So, you could do the reverse, then reverse back:
const arr = [
[1, 'cherry'],
[2, 'apple'],
[3, 'date'],
[4, 'elderberry'],
[5, 'banana'],
]
const sorted = arr.map(a => a.reverse()).sort().map(a => a.reverse())
sorted.forEach(e => console.log(e))
// [2, 'apple']
// [5, 'banana']
// [1, 'cherry']
// [3, 'date']
// [4, 'elderberry']
No, that is an un UGLY solution. And that would be prone to bugs if people change the data structure and there are probably some ugly edge cases. No one will hire you if that is how you do it. No, you need a custom sorting function, but as mentioned, you need to sort those strings properly. If this were an array of strings, the default sort function would work fine. But it isn’t, so it won’t.
The documentation (always read the docs) says that if the callback returns a number greater than 0, then a should come before b, less that 0 and b should come before a, and 0 means they are the same.
So, if you want to sort this, you need something like this:
const sortElements = (a, b) => {
if (a[1] > b[1]) return 1
if (a[1] < b[1]) return -1
return 0
}
const sorted = arr.sort(sortElements)
Or a common way to do something like this would be:
const sortElements = ([_dropA, a], [_dropB, b]) => a > b ? 1 : a < b ? -1 : 0
There are ways to make it more flexible and maintainable, but given the data we were, that will work.