-4
var a = [[11,"b"], [2,"b"], [11,"a"], [1,"a"], [1,"a"]];
a.sort();
alert(JSON.stringify(a)); 

gives:

[[1,"a"],[1,"a"],[11,"a"],[11,"b"],[2,"b"]]

how do I sort numerically?

Baz
  • 12,713
  • 38
  • 145
  • 268

2 Answers2

0

Assuming that the first element of the inner arrays will be always a number, which basing on you want to sort your array, you can just compare the first [0] from the inner arrays.

Note: a[0] - b[0] will sort elements in an ascending order.

const a = [[11,"b"], [2,"b"], [11,"a"], [1,"a"], [1,"a"]];

const r = a.slice().sort((a, b) => a[0] - b[0]);

console.log(JSON.stringify(r));
kind user
  • 40,029
  • 7
  • 67
  • 77
  • [`Array#sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) sorts in situ. the return of the same array looks like to get a new sorted array, which does not work like this. – Nina Scholz Nov 11 '17 at 12:23
-1

You can use underscoreJs _.sortby function

var a = [[11,"b"], [2,"b"], [11,"a"], [1,"a"], [1,"a"]];
var b = _.sortBy(a,function(val){
    return val[0];
});
console.log(JSON.stringify(b)); 
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
dwij
  • 694
  • 8
  • 17