0

I have an array with subarrays and wish to sort numerically by the first item in the subarrays.

Using sort() function:

arr = [[2,'text'],[5,'text'],[1,'text'],[3,'text'],[6,'text'],[4,'text'],
      [7,'text'],[9,'text'],[3,'text'],[1,'text'],[8,'text']];

arr.sort(function(a, b) {
    return a[0] < b[0];
});

I found that if the array contains less than 10 subarrays, the sort() function work good. But if the array contains more than 10 subarrays, then something goes wrong.

In this case, the array has 11 items, so the result generated by Chrome is:

[4, "text"]
[8, "text"]
[9, "text"]
[7, "text"]
[6, "text"]
[5, "text"]
[3, "text"]
[3, "text"]
[2, "text"]
[1, "text"]
[1, "text"]

The 4 should be at the middle of the array, not on the top.

Any idea why it happened? Thanks.

Cheng
  • 45
  • 5

2 Answers2

2

Here's the documentation for Array.prototype.sort. Your current code returns a boolean. Instead, the function should return a number, either less than zero for a to come before b, or greater for b to come before a (and 0 for no change). For greatest-to-least order, try this instead:

arr.sort(function(a, b) {
    return b[0] - a[0];
});
kingdaro
  • 11,528
  • 3
  • 34
  • 38
0

The function you pass to sort should return a number, positive if the first value is greater than the second, 0, if they're equal, negative if it's less than. So this would do:

arr.sort(function(a, b) {
    return b[0] - a[0];
});

or perhaps more simply, in modern JS:

arr.sort((a, b) => b[0] - a[0])
Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103