簡體   English   中英

如何在第一個值上對數組排序?

[英]How can I sort an array on the first value?

我有一個包含字符串和數組的數組。 每個字符串都與它旁邊的數組相關聯。 例如,字符串789與數組['111A','222B','333C']相關聯。 我想對字符串進行排序,同時保持數組綁定。

我試過使用sort()方法,當我的數組中只有字符串時,它會按順序進行排序,但是當我添加數組時,它會恢復為默認排序。

let myArry = [
  '789', 
  ['111A','222B','333C'], 
  '456',
  ['444E','555F','666G'], 
  '123',
  ['777H','888I','999J']
]

myArray.sort(function(a,b){
return a - b
})

最終,我希望數據看起來像這樣。

['123', ['777H', '888I','999J'],
'456', ['444E', '555F', '666G'],
'789', ['111A', '222B', '333C']]

您可以按對分組,對它們進行排序,然后得到一個平面數組。

 var array = ['789', ['111', '222', '333'], '456', ['444', '555', '666'], '123', ['777', '888', '999']], result = array .reduce((r, v, i) => { if (i % 2) r[r.length - 1].push(v); else r.push([v]); return r; }, []) .sort(([a], [b]) => a - b) .reduce((r, a) => r.concat(a), []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

您可以創建一個數組,以將找到的每個String的2個元素保持在一起,然后按字符串排序並應用concat以獲得類似於初始數組但按字符串排序的數組:

 let myArray = [ '789', ['111', '222', '333'], '456', ['444', '555', '666'], '123', ['777', '888', '999'], ]; const orderMyArrayByTheStrings = (myArray) => { const myArrayWithArrays = myArray .reduce((acc, el, index, array) => { if (!(el instanceof Array)) { return acc.push([el, array[index + 1]]) && acc; } else { return acc; } }, []) const myArraySortedByStrings = myArrayWithArrays.sort((a, b) => { return a[0] - b[0]; }) return [].concat.apply([], myArraySortedByStrings) } console.log(orderMyArrayByTheStrings(myArray)) 

您可以定義排序功能,您可以在其中更改項目類型-例如toString()

let myArray = [
    '789', 
    ['111','222','333'], 
    '456',
    ['444','555','666'], 
    '123',
    ['777','888','999']
];
myArray.sort((left,right)=>{
    if(left.toString() < right.toString()) {
        return -1;
    } else if(left.toString() > right.toString()) {
        return 1;
    } else {
        return 0;
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM