-4
var a = [[11,"b"], [2,"b"], [11,"a"], [1,"a"], [1,"a"]];
a.sort();
alert(JSON.stringify(a));
給出:排序號碼數字
[[1,"a"],[1,"a"],[11,"a"],[11,"b"],[2,"b"]]
我怎麼樣數值?
var a = [[11,"b"], [2,"b"], [11,"a"], [1,"a"], [1,"a"]];
a.sort();
alert(JSON.stringify(a));
給出:排序號碼數字
[[1,"a"],[1,"a"],[11,"a"],[11,"b"],[2,"b"]]
我怎麼樣數值?
假設內部數組的第一個元素將是總是一個數字,你要排序的數組,它立足,你可以比較來自內部陣列第一[0]
。
注意:a[0] - b[0]
將按升序對元素進行排序。
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));
可以使用underscoreJs _.sortby功能
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/[email protected]/lodash.min.js"></script>
['陣列#sort'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)就地排序。同一個數組的返回看起來像獲得一個新的已排序數組,它不能像這樣工作。 –