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?
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?
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));
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>