16、数组合并

  • 题一:

let ary1 = ['A1','A2','B1','B2','C1','C2','D1','D2']
let ary2 = ['A','B','C','D']
//因为使用arr.sort((a,b)=>a.localeCompare(b)),时候没有Z,ABCD这些会在最前面
ary2 = ary2.map(item=>item+'Z')
let arr = ary1.concat(ary2)
arr.sort((a,b)=>a.localeCompare(b)).map(item=>{
  return item.replace('Z','')    //去除Z
})

console.log(arr)    //["A1", "A2", "A", "B1", "B2", "B", "C1", "C2", "C", "D1", "D2", "D"]
  • 题二:
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++){
    let item2 = ary2[i]
  for(let j = 0;j<ary1.length;j++){
    let item1 = ary1[j]
    if(item1.includes(item2)){
        n = j;    //包含记录索引,后面有包含会更新这个值。保存最后一项匹配的索引
    }
  }
  //把当前的值插入到索引的后面
  ary1.splice(n+1,0,item2)    //从n+1删除0项,将item2插入n+1的前面,也就相当于n后面插入n+1
}
console.log(ary1)    //["D1", "D2", "D", "A1", "A2", "A", "C1", "C2", "C", "B1", "B2", "B"]

results matching ""

    No results matching ""