我有两个包含字符串数据的数组:
abc
我需要.concat这些数组和.sort像这样:
bca
排序标准是我需要具有相同"颜色目录"的数组元素对。和相同的文件名。
我试过这个:
var AA = ["~/80/Blue/1.png","~/80/Blue/2.png","~/80/Black/1.png","~/80/Black/2.png"];
var BB = ["~/81/Blue/1.png","~/81/Blue/2.png","~/81/Black/1.png","~/81/Black/2.png"];
答案 0 :(得分:0)
var AA = ["~/80/Blue/1.png","~/80/Blue/2.png","~/80/Black/1.png","~/80/Black/2.png"];
var BB = ["~/81/Blue/1.png","~/81/Blue/2.png","~/81/Black/1.png","~/81/Black/2.png"];
var CC = [];
var longestArr = 0;
if (AA.length > BB.length) {
longestArr = AA.length;
} else {
longestArr = BB.length;
}
for (var i = 0; i < longestArr; i++) {
if (AA[i]!==undefined) {
CC.push(AA[i]);
};
if (BB[i]!==undefined) {
CC.push(BB[i]);
};
}
这就是你想要的吗?
答案 1 :(得分:0)
以下是如何压缩两个长度相等的数组。
var CC = AA.reduce(function(result, value, i) {
return result.concat(value, BB[i]);
}, []);
JSFiddle演示:https://jsfiddle.net/uh0q2eqb/
以下是如何根据目录名称和文件名将相等长度的数组排序为字符串,然后压缩它们。
AA.sort(comparator);
BB.sort(comparator);
var CC = AA.reduce(function(result, value, i) {
return result.concat(value, BB[i]);
}, []);
function comparator(a, b) {
var A = a.split('/').splice(2).join('/');
var B = b.split('/').splice(2).join('/');
if (A > B) {
return 1;
} else if (A < B) {
return -1;
} else {
return 0;
}
}
JSFiddle演示:https://jsfiddle.net/uh0q2eqb/1/
答案 2 :(得分:0)
首先,连接两个数组,然后使用Arrays.sort方法进行排序,方法是将所需的排序逻辑作为sortFunction参数传递。
var AA = ["~/80/Blue/1.png","~/80/Blue/2.png","~/80/Black/1.png","~/80/Black/2.png"];
var BB = ["~/81/Blue/1.png","~/81/Blue/2.png","~/81/Black/1.png","~/81/Black/2.png"];
var CC = [];
var CC = AA.concat(BB);
function string_split_comparator(a, b) {
var A_colorFile = a.split('/').splice(2).join('/'); /* Blue/1.png */
var B_colorFile = b.split('/').splice(2).join('/');
var A_directoryNum = a.split('/')[1]; /* 80 */
var B_directoryNum = b.split('/')[1];
if(A_colorFile !== B_colorFile){
return A_colorFile < B_colorFile;
} else{
return A_directoryNum < B_directoryNum
}
}
CC.sort(string_split_comparator);