Govind Rai Govind Rai - 10 months ago 40
Javascript Question

Javascript Console returns incorrect sorted array

I entered the following code into the chrome console.

var array = [25,7,8,41];

It returns
. What's going on?

Answer Source

The sort() method sorts the items of an array.

The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).

By default, the sort() method sorts the values as strings in alphabetical and ascending order.

This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

Because of this, the sort() method will produce an incorrect result when sorting numbers.

If you would like this to be corrected you can write a comparison function as the first parameter passed to the sort method. There is one listed in the reference!

EDIT: Posted here for future cases...

var points = [40, 100, 1, 5, 25, 10];
function myFunction() {
    points.sort(function(a, b){return a-b});