繁体   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