-7

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"]
3
  • 2
    You need sort().reverse() for that (reverse reverses, it doesn't sort) Commented Jul 18, 2019 at 9:06
  • reverse and sort are not alias, they are different Commented Jul 18, 2019 at 9:07
  • Additional note: Keep in mind that strings and numbers do not sort the same way. "11" < "9" = true and 11 < 9 = false. Commented Jul 18, 2019 at 9:12

2 Answers 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
)

Sign up to request clarification or add additional context in comments.

2 Comments

you've marked the sorting function the wrong way around (a,b) => a-b is asc. and I'd make a copy before sorting the Array array.slice().sort(...), or the console.log will show only the last order.
@Thomas thanks. Made it to 2 separate logs
2

reverse with sort function like this:

console.log(["4", "2", "5", "3"].sort().reverse())

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.