[['10','8'],['11','4'],['18','7'],['7','6'],['8','7'],['9','5']]
JavaScript 這樣的陣列怎麼弄成
[['7','6'],['8','7'],['9','5'],['10',' 8'],['11','4'],['18','7']]
這樣的順序排列
大神
我想大声告诉你2017-06-12 09:29:27
array = [['10','8'],['11','4'],['18','7'],['7','6'],['8',' 7'],['9','5']]
function sortNumber(a,b){return a[0]-b[0]}
let newArray = array.sort(sortNumber)
newArray 應該就是你要的結果了
PHP中文网2017-06-12 09:29:27
你這個二維數組的排列的結果,好像是用的數組中的每個元素(數組)中的第一個下標的元素去比較的,那就轉化成一個一維數組排序不就不好了嗎?一維數組排好序,再將原二維數組利用index對應上一維數組排序。
邏輯實現想法:
var twoArray = [['10','8'],['11','4'],['18','7'],['7','6'], ['8','7'],['9','5']];
var oneArray = [];
twoArray.map(function (item ,index) {
oneArray.push({value: item[0], index: index});
});
console.log(oneArray);
function sortNumber (a, b) {
return a.value - b.value;
}
console.log(oneArray.sort(sortNumber));
// 此时的oneArray已排好序
var newTwoArray = [];
oneArray.map(function (item) {
newTwoArray.push(twoArray[item.index]);
});
console.log(newTwoArray);// 即你要的排序