//有规律的合并两个数组
// ['A1','A2','A3','B1','B2','C1','C2','C3','D1','D2']-数组1
// ['A','B','C','D']-数组2
// 合并为 ['A1','A2','A3','A','B1','B2',"B",'C1','C2','C3',"C",'D1','D2',"D"]
const easyCloneObj=obj=>JSON.parse(JSON.stringify(obj))
// 1.遍历数组2,使用数组2的元素作为正则,匹配数组1
function combine1(arr1,arr2){
let currentIndex=0
let result=easyCloneObj(arr1)
for(let i=0;i<arr2.length;i++){
const reg=new RegExp(arr2[i])
while(currentIndex++<result.length){
if(!reg.test(result[currentIndex])){
result.splice(currentIndex,0,arr2[i])
break;
}
}
}
// console.log(arr1)
return result
}
// const arr3=combine1(['A1','A2','A3','B1','B2','C1','C2','C3','D1','D2'],['A','B','C','D'])
// console.log(arr3)
//遍历数组1,使用数组1首字符去匹配数组二的元素
function combine2(arr1,arr2){
let result=[]
let j=0
for(let i=0;i<arr1.length;i++){
const char=arr1[i][0]
if(char==arr2[j]){
result.push(arr1[i])
}else{
result.push(arr2[j])
result.push(arr1[i])
j++
}
//当最后一轮循环中不会再有别的字符,进入不了else分支
//导致arr2的最后一个元素没有push进来需要特殊处理
if(i==arr1.length-1){
result.push(arr2[j])
}
}
return result
}
const arr4=combine2(['A1','A2','A3','B1','B2','C1','C2','C3','D1','D2'],['A','B','C','D'])
console.log(arr4)