I have an array ["4", "2", "5", "3"], why the sort function works properly but not the reverse one?
["4", "2", "5", "3"].sort(); //gives me ["2", "3", "4", "5"]
["4", "2", "5", "3"].reverse(); //gives me ["3", "5", "2", "4"]
From Array.prototype.reverse()
The
reverse()method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.
It just reverses a given array and it has nothing to do with sorting. You can do array.sort().reverse()
BTW, ["4", "2", "5", "3"].sort() sorts the array lexically.
console.log(
["4", "2", "5", "40", "3"].sort() // ["2","3","4","40","5"]
)
If you want to sort the given array based on their numeric values, you'd have to do:
const array = ["4", "2", "5", "3"]
console.log(
array.sort((a, b) => a - b) // asc
)
console.log(
array.sort((a, b) => b - a) // desc
)
sort().reverse()for that (reverse reverses, it doesn't sort)reverseandsortare not alias, they are different"11" < "9" = trueand11 < 9 = false.