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.
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.Reference:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort