Jim Johnson
Jim Johnson

Reputation: 2609

Why does numberArray.sort() not sort numbers correctly in JavaScript?

I'm practicing the data visualization library d3.js, and I am using a random data generator identical to the following:

function generateRandomData() {
    var i,
        data = [];
    for (i = 0; i < 100; i += 1) {
        data.push(Math.random() * 100);
    }
    return data;
}

I store the value and try to sort it as shown below:

var data = generateRandomData();
data.sort();

Unfortunately, the sorted dataset is not sorted completely - some of the values are actually incorrect. For example, I would have numbers such as [12, 15, 18, 21, 3, 18 ...]. What is the cause of the sort function's inaccuracy?

Note: I found a proper solution, which solved my problem:

data.sort(function (a, b) { return b - a; });

I simply want to know why sort() is unreliable.

Upvotes: 2

Views: 622

Answers (1)

nhahtdh
nhahtdh

Reputation: 56809

sort() function considers everything in the Array as String if it is called without custom ordering function.

The only exception is undefined, which is from Javascript 1.2 always the "largest" item in the sorted array.

[void(0),342,4.5,"ahahaha",null,"zzz", "nen", "nup", 0/0, "KDSFL", "-sdfh",-3324, "-%",Array.prototype.sort,window,Array.zzz,"[oooooo]", "undefined",0].sort()

Reference:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

Upvotes: 2

Related Questions