a=[[a,b,c],[a,d,e][b,c,d]],JS把二维数组内每个数组第一个相等的数组合并,合并后a=[[a,b,c,d,e],[b,c,d]].怎么写代码?
var a=[['a','b','c'],['a','d','e'],['b','c','d']];
var result = [];
var getIndex = function(result, arr) {
for (var i = 0; i < result.length; i++) {
if (result[i] && result[i][0] == arr[0]) {
return i;
}
}
return -1;
}
var merge = function(arr1, arr2) {
for (var i = 1; i < arr2.length; i++) {
arr1.push(arr2[i]);
}
}
for (var i = 0; i < a.length; i++) {
var index = getIndex(result, a[i]);
//console.log(index);
if (index >= 0) {
merge(result[index], a[i]);
} else {
result.push(a[i]);
}
}
return result;
var result = [];
var getIndex = function(result, arr) {
for (var i = 0; i < result.length; i++) {
if (result[i] && result[i][0] == arr[0]) {
return i;
}
}
return -1;
}
var merge = function(arr1, arr2) {
for (var i = 1; i < arr2.length; i++) {
arr1.push(arr2[i]);
}
}
for (var i = 0; i < a.length; i++) {
var index = getIndex(result, a[i]);
//console.log(index);
if (index >= 0) {
merge(result[index], a[i]);
} else {
result.push(a[i]);
}
}
return result;
温馨提示:答案为网友推荐,仅供参考