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.