As others have pointed out, a major issue with your version is that it uses the mutating sort
. Although you could fix this by inserting a slice(0)
or some such to clone the array, and then writing an index-by-index equality tester, it's much easier to simply test if each successive entry is larger than the previous one.
Perhaps the most elegant way to do that is through recursion. Here's one example:
const inAscOrder = (a) => a.length < 2 || (a[0] < a[1] && inAscOrder(a.slice(1)))
This might not be workable for larger arrays because of Javascript's recursion depth limits. But an iterative version of the same thing is fairly straightforward:
const inAscOrder = (a) => {
if (a.length < 2) {return true}
for (let i = 1; i < a.length; i++) {
if (a[i -1] > a[i]) {return false}
}
return true
}