我有一个包含字符串和数组的数组。每个字符串都与它旁边的数组相关联。例如,字符串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']]
答案 0 :(得分:1)
您可以按对分组,对它们进行排序,并获得平面阵列。
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; }
答案 1 :(得分: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))
答案 2 :(得分:-2)
您可以定义排序功能,在其中可以更改项目类型-例如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;
}
});