Sort Array in JavaScript [duplicate]

1

I have an Array with decreasing even numbers:

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

When I call a.sort() , it returns the following:

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

This ordering is not correct. How can I sort in ascending order correctly?

    
asked by anonymous 27.11.2017 / 19:16

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 Comparison function is not informed, the elements will be sorted   according to their conversion to text and the comparative text in the   unicode punctuation of the converted text. For example, "cherry" comes before   of banana". In a numerical order, 9 comes before 80, but because   numbers are converted to text, and "80" comes before "9" in the   Unicode ordering.

    
27.11.2017 / 19:18