Sort Array in Javascript

Asked

Viewed 963 times

1

I have an Array with even numbers decreasing:

var a = [20, 18, 10, 8, 6, 4, 2, 0]

when I call a.sort(), he returns me the following:

[0, 10, 18, 2, 20, 4, 6, 8]

This ordination is not correct. How can I order by ascending order correctly?

1 answer

6

You need to pass the comparison function:

var a = [20, 18, 10, 8, 6, 4, 2, 0]
a.sort( (a,b) => a - b );
console.log(a);

The reason for this is:

If function according to its conversion to text and the text compared in Unicode score of the converted text. For example, "Cherry" comes before of "banana". In a numerical ordering, 9 comes before 80, but because the numbers are converted to text and, "80" comes before "9" in unicode ordination.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.