2

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

6 Comments

Unfortunately, while correct (+1), this disagrees with the "results" given in the post...
OP's example result of [12, 15, 18, 21, 3, 18 ...] is likely just an example, as running sort() on that array (minus the ellipses) results in [12,15,18,18,21,3], which is the proper sort order assuming all values are strings
@pst true; i thought you were questioning the validity of the answer
@jackwanders Yes, you're right, my "result" was just an example, because I didn't want to copy and paste the long result that I had. So why is it that it matters that they're strings and not numbers?
If you don't provide sort() with a sorting function, it converts all values to strings and runs a alphabetic comparison. Therefore, 12 < 2. If you want to sort numerically, you have to provide a sorting function
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.