13、数组合并

得到["A", "A1", "A2", "B", "B1", "B2", "C", "C1", "C2", "D", "D1", "D2"]

let ary1 = ['A1','A2','B1','B2','C1','C2','D1','D2']
let ary2 = ['A','B','C','D']

let arr = ary1.concat(ary2).sort((a,b)=>{
  return a.localeCompare(b)
})
console.log(arr)        //["A", "A1", "A2", "B", "B1", "B2", "C", "C1", "C2", "D", "D1", "D2"]

localeCompare先比较第一个再比较第二个

更进一步:得到["A1", "A2", "A", "B1", "B2", "B", "C1", "C2", "C", "D1", "D2", "D"]

思路:加一个大的,然后排序最后去除这个加入的str

let ary1 = ['A1','A2','B1','B2','C1','C2','D1','D2']
let ary2 = ['A','B','C','D']

ary2 = ary2.map(item=>item+'3')

let arr = ary1.concat(ary2).sort((a,b)=>{
  return a.localeCompare(b)
})
console.log(arr) //["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3", "D1", "D2", "D3"]
arr = arr.map(item=>{
  return item.replace('3','')
})
console.log(arr)    //["A1", "A2", "A", "B1", "B2", "B", "C1", "C2", "C", "D1", "D2", "D"]

进一步:如果原有数组顺序不一致,但是排序后必须顺序不变,如下:

思路:将ary2中的元素一个一个往ary1中插入,遍历两个数组,ary2中的元素依次在ary1中进行查找,看是否包含,包含的话记录索引,插入最后一个索引值后面

let ary1 = ['D1','D2','A1','A2','C1','C2','B1','B2']
let ary2 = ['B','A','D','C']
//要求得到 ['D1','D2','D','A1','A2','A','C1','C2','C','B1','B2','B']

 let n = 0;
 for(let i = 0;i < ary2.length;i++){
   for(let j = 0;j < ary1.length;j++){
     if(ary1[j].includes(ary2[i])){
       n = j;
     }
   }
   ary1.splice(n+1,0,ary2[i])
   n = 0;
 }
console.log(ary1)// ["D1", "D2", "D", "A1", "A2", "A", "C1", "C2", "C", "B1", "B2", "B"]

results matching ""

    No results matching ""