是不是
并集
的意思呀?
哎呀,数组可以包含乱七八糟的元素呀,很复杂的呀,部分代码如下:
// 求2个数组的并集
$._combineTwoArrays = function(first, second) {
if (!$.isArray(first) || !$.isArray(second)) {
throw new Error('$._combineTwoArrays function must be set two Array type params')
}
var merged = first.concat(second), tlen = merged.length, combined = []
for (var i = 0i <tleni++) {
var elem = merged.shift(), flag = false
if (i === 0)
combined.push(elem)
for (var j = 0j <combined.lengthj++) {
var c = combined[j]
if ($.isArray(elem)) {
if (!$.isArray(c)) {
flag = true
}
else if (!$._isTheSameArrays(elem, c)) {
flag = true
} else {
flag = false
break
}
} else if ($.type(elem) === 'object') {
if (!$._isTheSameObjects(elem, c)) {
flag = true
} else {
flag = false
break
}
} else {
if (c !== elem) {
flag = true
} else {
flag = false
break
}
}
}
if (flag)
combined.push(elem)
}
return combined
}
首先考虑的是两个数组之间靠什么来关联:根据newArr得出: province的id对应的city里面的pid
所以遍历数组时候合并的逻辑: id ==pid.然后合为新数组的一个元素。
var newArr=[]
function combineArr(arr1, arr2){
var len = arr1.length
for(var i=0i<leni++){
if(arr1[i].id == arr2[i].pid){
var obj = {}
obj['name']=arr1[i].name
obj['city'] = arr2[i].name
newArr.push(obj)
}
return newArr
}
}