第 30 题:请把俩个数组 [A1, A2, B1, B2, C1, C2, D1, D2] 和 [A, B, C, D],合并为 [A1, A2, A, B1, B2, B, C1, C2, C, D1, D2, D]

发布于 2022-07-12 19:08:49 字数 720 浏览 1123 评论 53

function concatArr (arr1, arr2) {
   const arr = [...arr1];
  let currIndex = 0;
 for (let i = 0; i < arr2.length; i++) {
    const RE = new RegExp(arr2[i])
    while(currIndex < arr.length) {
      ++currIndex
      if (!RE.test(arr[currIndex])) {
         arr.splice(currIndex, 0, a2[i])
         break;
       }
     }
   }
  return arr
 }
 var a1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'] 
 var a2 = ['A', 'B', 'C', 'D']
 const arr = concatArr(a1, a2)
 console.log(a1) // ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'] 
 console.log(a2) // ['A', 'B', 'C', 'D']
 console.log(arr) // ['A1', 'A2', 'A', B1', 'B2', 'B', C1', 'C2', 'C', D1', 'D2', 'D']

以上是我个人想法,有更好方法的欢迎讨论

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(53

一城柳絮吹成雪 2022-05-04 13:57:18
var arr1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
var arr2 = ['A', 'B', 'C', 'D']

const func = (arr1, arr2) => arr2.reduce((acc, cur) => [...acc, ...arr1.filter(item => item.startsWith(cur)), cur], [])
§普罗旺斯的薰衣草 2022-05-04 13:57:18

题目测试用例有点少规则太模糊了。。

写一个用sort的吧

const arr1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'];
const arr2 = ['A', 'B', 'C', 'D'];
const arr3 = arr1.concat(arr2);
const comp = function(a,b){
    const len = Math.max(a.length, b.length);
    for(let i = 0; i < len; i++){
        if(a.charAt(i) === "") return 1;
        if(b.charAt(i) === "") return -1;
        if(a.charAt(i) !== b.charAt(i)){
            return a.charAt(i) > b.charAt(i) ? 1:-1;
        }
    }
    return 0;
}
arr3.sort(comp);
console.log(arr3);
人事已非 2022-05-04 13:57:18
let a1 =  ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
let a2 = ['A', 'B', 'C', 'D'].map((item) => {
  return item + 3
})

let a3 = [...a1, ...a2].sort().map((item) => {
  if(item.includes('3')){
    return item.split('')[0]
  }
  return item
})
纵性 2022-05-04 13:57:18
let a =  ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
let b = ['A', 'B', 'C', 'D']
let arr = a.concat(b).sort()

let tmp = '', r = []
arr.forEach((item, index, a) => {
    if (item.length === 1 && tmp === '') {
	tmp = a[0]
    } else if (item.length === 1) {
	r.push(tmp)
	tmp = item
    } else {
	r.push(item)
    }

    // 这里是将最后获取的单个值,push到最后。
    if (index === a.length -1) {
	r.push(tmp)
    }
})

console.log(r) // ["A1", "A2", "A", "B1", "B2", "B", "C1", "C2", "C", "D1", "D2", "D"]

想法是将合并后的数组sort完,将如A、B替换到A1等的后面。这样的好处是只需要一次遍历。缺点是仅仅针对题目的数据格式,即A1 和 A的字符串长度。

其实一开始想到的是下面这种替换合并后的数组。不过感觉不如新起一个数组

let a =  ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
let b = ['A', 'B', 'C', 'D']
let arr = a.concat(b).sort()
let tmp = ''
arr.forEach((item, index, a) => {    
    if(item.length === 1 && tmp === '') {
        tmp = a.splice(0, 1)
    } else if(item.length === 1) {
        tmp = a.splice(index, 1, ...tmp)
    } else if(index === a.length -1) {
    	a.push(...tmp)
    }
})
console.log(arr) // ["A1", "A2", "A", "B1", "B2", "B", "C1", "C2", "C", "D1", "D2", "D"]
内心荒芜 2022-05-04 13:57:18
let arr1 = ['A1', 'A2', 'A3', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'];
let arr2 = ['A', 'B', 'C', 'D','E'];
let newArr1 = [];
newArr1 = arr2.map((item)=>{
	let arr3 = arr1.filter((value)=> value.startsWith(item));
	arr3.push(item);
	return arr3
})
console.log(newArr1.join(',').split(','));
//["A1", "A2", "A3", "A", "B1", "B2", "B", "C1", "C2", "C", "D1", "D2", "D", "E"]
寂寞美少年 2022-05-04 13:57:18
  const arr1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
  const arr2 = ['A', 'B', 'C', 'D']
  const arr = [...arr1,...arr2]
  arr.sort((a,b)=>{
    // 用字符 : 去做默认占位,因为它 的 ASCII 码大于数字9
    if(a.length > b.length) {
      b = b.padEnd(a.length,':')
    }else {
      a = a.padEnd(b.length,':')
    }
    if(a>b) return 1
    if(a<b) return -1
    return 0
  })
 console.log(arr)
染火枫林 2022-05-04 13:57:18
const a = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'];
const b = ['A', 'B', 'C', 'D'];
// ['A1', 'A2', 'A', 'B1', 'B2', 'B', 'C1', 'C2', 'C', 'D1', 'D2', 'D'];

for (let i = 0; i < b.length; i++) {
  const n = b[i];
  const xx = i + (2 * (i + 1));
  a.splice(xx, 0, n);
}

console.log(a);
双马尾 2022-05-04 13:57:18
console.log(
  function concatArr() {
    return [].concat.apply([], arguments).sort((a, b) => {
      // 如果a 小 在前 则返回 -1
      return a[0] < b[0]
        ? -1
        : a[1]
          ? 1
          : a[1] - b[1];
    });
  }(['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'], ['A', 'B', 'C', 'D'])
);
东京女 2022-05-04 13:57:18

//利用字符串的charCodeAt 进行排序,some 只要找到一个符合条件的就不要在进行循环了
var array = ['A1', 'A2','B1', 'B2', 'C1', 'C2', 'D1', 'D2']
var array1 = ['A','B','C','D']
var result = array//重新定义一个新的数组,不影响原来的数组
var array2 = array.join('').split('')
array1.some((x,index)=>{
array2.some((y,key)=>{
if(y.charCodeAt()>x.charCodeAt()){
return result.splice((key/2)+index,0,x)
}
})
})
result.push(array1[array1.length-1])

南冥有猫 2022-05-04 13:57:18

`
var arr1 = ["A1", "A2", "B1", "B2", "C1", "C2", "D1", "D2"]
var arr2 = ["A", "B", "C", "D"]

let count = 2
arr2.forEach((item, index) => {
arr1.splice(index * 2 + count, 0, item)
count++
})
console.log(arr1)
`
以上是我觉得相对简单的,可以看出arr1相应的规律是2的平方阶,然后每次插入新元素都会加1,所以用count++来处理

旧时光的。容颜 2022-05-04 13:57:18

const a1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'];
const a2 = ['A', 'B', 'C', 'D'].map(item=>{ return item + '3'; });
const a3 = [...a1,...a2].sort().map(item=>{ return item.split('3')[0] });
console.log(a3,'a3'); // ["A1", "A2", "A", "B1", "B2", "B", "C1", "C2", "C", "D1", "D2", "D"] "a3"

吃颗糖壮壮胆 2022-05-04 13:57:18
const arr1 = ["A1", "A2", "B1", "B2", "C1", "C2", "D1", "D2"];
const arr2 = ["A", "B", "C", "D"];
const arr=[...arr1,...arr2].sort((a,b)=>{
    if(a.length===1){
        a+="3"
    }
    if(b.length===1){
        b+="3"
    }
    return a.localeCompare(b)
})
console.log(arr);

合并排序就完事了啊;考察的什么呢?

你的笑 2022-05-04 13:57:18

function concatArr(a1, a2) {
var reg = /[^0-9]/ig;
return [...a1, ...a2].sort((a, b) => {
var num1 = a.replace(reg, ' ').trim().split(' ')[0];
var num2 = b.replace(reg, ' ').trim().split(' ')[0];
var ascoll1 = a.charCodeAt();
var ascoll2 = b.charCodeAt();
if (!num1 || !num2) {
if (ascoll1 !== ascoll2) return ascoll1 - ascoll2;
if (!num1) return 1
return -1
}
return (ascoll1 + num1) - (ascoll1 + num2)
})
}

诗酒趁年少 2022-05-04 13:57:18
const arr2 = ["A", "B", "C", "D"];
const result = [...arr1, ...arr2].sort((a, b) => {
  const a_code = a.charCodeAt(0);
  const a_num = a.substring(1, a.length) || Infinity;
  const b_code = b.charCodeAt(0);
  const b_num = b.substring(1, b.length) || Infinity;
  if (a_code === b_code) {
    return a_num - b_num;
  }
  return a_code - b_code;
});

console.log(result);
何必那么◎矫情 2022-05-04 13:57:18

let arrA = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'];
let arrB = ['A', 'B', 'C', 'D'];

function concatAndSort(arrA,arrB){
    let arrC = [].concat(arrA);
    let j = 0;
    let count = 0;
    for(let i=0;i<arrB.length;i++){
        console.log(j);
        while(j<arrA.length){
            let astr = arrA[j],bstr = arrB[i];
            if(astr.startsWith(bstr)){
                j++;
            }else{
                if(j===arrA.length-1){
                    arrC.push(bstr);
                    break;
                }else{
                    arrC.splice(j+count,0,bstr);
                    count++;
                    break;
                }
            }
        }
    
    }
    return arrC;
}
let arrC = concatAndSort(arrA,arrB);
console.log(arrC);
-梦醒时光 2022-05-04 13:57:18

使用了双指针:

若水微香 2022-05-04 13:57:18
var a1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
var a2 = ['A', 'B', 'C', 'D']
function mergeArray1(a1, a2) {
    //时间复杂度过高不予考虑,估计O(n^3+n)
    //思路先给a2填充3,排序后再去掉3
    a2 = a2.map((item) => item + 3)
    let temp = [...a1, ...a2]
    return temp.sort().map((item) => {
        if (item.includes('3')) {
            return item.slice(0, 1)
        }
        return item
    })

}
function mergeArray2(a1, a2) {
    //时间复杂度过高不予考虑,估计O(n^2)
    //思路双重排序
    // return [...a1, ...a2].sort().sort(function (a, b) {
    //     if (a.charAt(0) == b.charAt(0) && a.length > b.length) {
    //         return -1
    //     }
    // })
    //个人认为最好的解法,大概O(n)
    //思路为一次排序,||:前者为真就不看后者,先根据首字母判断排序,在根据长短把短的排后面,最后根据尾号排序
    //
    return [...a1, ...a2].sort(
        (a, b) => (
            a.codePointAt(0) - b.codePointAt(0) ||
            b.length - a.length ||
            a.codePointAt(1) - b.codePointAt(1)
        )
    )
}
console.log(mergeArray2(a1, a2));
温暖的光 2022-05-04 13:57:18
let a1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'],
	a2 = ['A', 'B', 'C', 'D'],
	a3 = [...a1],	//结果数组
	len = a1.length + a2.length;	//总长度
for (let i = 2; i < len; i += 3) {
	a3.splice(i, 0, a2.shift())
}
console.log(a3);
稀香 2022-05-04 13:57:18

['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'].reduce((a,c,i,r)=>(a.push(c),(r.map(z=>z.charAt(0)).lastIndexOf(c.charAt(0))===i)&&a.push(c.charAt(0)),a),[])

天邊彩虹〆 2022-05-04 13:57:18

更简单的一种写法,希望对你有所帮助

let arr1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'] 
let arr2 = ['A', 'B', 'C', 'D']
let arr = arr1.concat(arr2)
arr.sort((a,b)=>a[0]<b[0]?-1:1)
console.log(arr);// ['A1', 'A2', 'A', 'B1', 'B2', 'B', 'C1', 'C2', 'C', 'D1', 'D2', 'D']
风为裳 2022-05-04 13:57:18

let arr1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'];
let arr2 = ['A', 'B', 'C', 'D'];
let arr3 = [];
let obj = {};
arr2.forEach((item) => {
obj[item] = [];
});
arr1.forEach((item) => {
arr2.forEach((it) => {
if (item.indexOf(it) !== -1) {
obj[it].push(item);
}
});
});
Object.keys(obj).forEach((key) => {
arr3.push(obj[key]);
arr3.push(key);
});
console.log(arr3.flat(Infinity));

白芷 2022-05-04 13:57:18

var arrOne =["A1", "A2", "B1", "B2", "C1", "C2", "D1", "D2"]; var arrTwo = ['A', 'B', 'C', 'D'];

for (let i = 0; i < arrTwo.length; i++) { let re = new RegExp(arrTwo[i], 'g'); for (let x = arrOne.length; x > 0; x--) { if(re.test(arrOne[x])){ arrOne.splice(x+1,0,arrTwo[i]) } } } console.log(arrOne);

这样是否可以呢?

我想请教下,为啥test加了g全局后,A2匹配不到

行至春深 2022-05-04 13:57:18
function orderList(arr1, arr2) {
  let arr = [...arr1, ...arr2];
  return arr.sort((a, b) => {
    if (a.length > b.length || a[0] < b[0]) {
      return -1;
    }
  });
}
花间憩 2022-05-04 13:57:18

想到做的一个需求,插入广告位,在1、3、6插入广告数据,跟这个应该是一个道理

var a = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'];
var b = ['A', 'B', 'C', 'D'];
let arr = [...a];
let index = 0;
for (let i = 0; i < a.length; i++) {
  if( i % 2 == 1 ) {
    let ind = i + 1 + index;
    arr.splice(ind, 0, b[index]);
    index ++;
  }
}
console.log(arr);

image.png

〆昔梦 2022-05-04 13:57:18

function fn (arr1, arr2) {
let arr = arr1.concat(arr2)
arr = arr.sort((a, b) => {
let a1 = a.split('')
let b1 = b.split('')
let flag = a1[0] > b1[0]
if (flag) {
return flag
} else {
return (a[1] ? a[1] : 0) - (b[1] ? b[1] : 0)
}
})
return arr
}

let arr1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
let arr2 = ['A', 'B', 'C', 'D']
fn(arr1, arr2)

花开浅夏 2022-05-04 13:57:18
const a = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
const b = ['A', 'B', 'C', 'D']

// 方法1:

let c = [...a, ...b.map((str) => str + 3)]
  .sort()
  .map((str) => str.replace('3', ''))
console.log(c)

// 方法2:
// 用栈来保存当前处理的首字母, 先后遍历a, b , 将元素添加到结果数组
function merge(a, b) {
  const result = []
  const stack = []
  const getTop = () => {
    return stack.length === 0 ? null : stack[stack.length - 1]
  }
  // 遍历数组a , 并获取首字母, 添加到栈
  for (let i = 0; i < a.length; i++) {
    const strA = a[i]

    // 栈中保存当前处理的是哪个字母, 如果栈空则将当前首字母入栈
    const startLetter = strA[0]
    if (!getTop()) {
      stack.push(startLetter)
    }

    // console.log(`startLetter === stackTop, ${startLetter}, ${getTop()}`)
    // 如果A数组当前字符串的首字母和栈顶相同则放到结果数组
    // console.log(`startLetterNext ${startLetterNext}, ${getTop()}`)
    if (startLetter === getTop()) {
      result.push(strA)
    }

    // 且判断当前A数组元素后面的元素是否变化, 如果变化则把B数组元素放进来
    const startLetterNext = a[i + 1] && a[i + 1][0] // 结束时 则是undefined , 正好不等于栈顶, 也会处理循环b数组
    if (startLetterNext !== getTop()) {
      for (strB of b) {
        if (strB[0] === getTop()) {
          result.push(strB)
        }
      }
      // b 数组元素插入完毕, 则该首字母处理完毕, 出栈
      stack.pop()
    }
  }
  return result
}

console.log(merge(a, b))
等风来 2022-05-04 13:57:18

let a1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
let a2 = ['A', 'B', 'C', 'D']
let a3 = a2.reduce((pre, item, index)=>{
return [...pre, a1[2 * index], a1[2 * index + 1], item]
}, [])

console.log(a3)

七色彩虹 2022-05-04 13:57:18
//位置等差数列    
let a1=['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'] ;
let a2=['A', 'B', 'C', 'D'];
// 期望: ['A1', 'A2', 'A', 'B1', 'B2', 'B', 'C1', 'C2', 'C', 'D1', 'D2', 'D']。
let num=0;
for (let i = 0; i < a2.length; i++) {
  num=num+2;
  a1.splice(num,0,a2[i]);
  num++
}
//a1 = ['A1', 'A2', 'A', 'B1', 'B2', 'B', 'C1', 'C2', 'C', 'D1', 'D2', 'D']
二智少女猫性小仙女 2022-05-04 13:57:18

实测通过,写的很墨迹 ,但是简单易懂
`var arr = ['A3', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
var arr2 = ['A', 'B', 'C', 'D','A1']
const sort = (arr,arr2)=> {
let arr3 = []
//做一个空数组
arr.forEach((ele,index) => {
arr3.push(ele.substring(1) !== ' '?{
value1:ele.charAt(0),
value2:ele.substring(1)
}:{
value1:ele.charAt(0),
value2:Number.MAX_SAFE_INTEGER
})
});
arr2.forEach((ele,index) => {
arr3.push(ele.substring(1) !== ''?{
value1:ele.charAt(0),
value2:ele.substring(1)
}:{
value1:ele.charAt(0),
value2:Number.MAX_SAFE_INTEGER
})
});

arr3.sort(function (a, b) {
return (a.value2 - b.value2)
});

arr3.sort(function (a, b) {
let A = a.value1
let B = b.value1
if (A < B) {
return -1;
}
if (A > B) {
return 1;
}

// must be equal
return 0;
});

let arr4 = []
arr3.forEach((ele,idx)=>{
if(ele.value2 == Number.MAX_SAFE_INTEGER){
ele.value2 =' '
}
ele.value1= ele.value1 + ele.value2 + ' '
arr4.push(ele.value1)
})
return arr4
}
console.log(sort(arr,arr2))`

小女人ら 2022-05-04 13:57:18

思路

  • 遍历添加的列表,把需要塞进list1的子项筛选出来
  • 然后再合到list1中

可能要注意的点

  • 这个的顺序是按照list2来的,如果需要按list1来的话,需要去遍历list1,然后再添加list2的子项
function convert() {
  let res = []
  const list1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
  const list2 = ['A', 'B', 'C', 'D']

  for (const item of list2) {
    const containList = list1.filter((subItem) => subItem.includes(item))
    res = [...res, ...containList, item]
  }

  return res
}

console.log(convert())
深海夜未眠 2022-05-04 13:57:18
var a = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
var b = ['A', 'B', 'C', 'D']

a.concat(b).sort(function (a, b) {
    return (a.charCodeAt(0) - b.charCodeAt(0)) || b.length - a.length || a[1] - b[1];
})
把昨日还给我 2022-05-04 13:57:18
const a = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'];
const b = ['A', 'B', 'C', 'D'];

function merge(arr1, arr2) {
  const res = [];
  while (arr1.length && arr2.length) {
    while (arr1.length && arr1[0][0] === arr2[0]) {
      res.push(arr1.shift());
    }
    res.push(arr2.shift());
  }
  res.push(...arr2);
  return res;
}

merge(a, b);
奶茶°白久 2022-05-04 13:57:17

其实解法很简单的

let arr1 = ["A1", "A2", "B1", "B2", "C1", "C2", "D1", "D2"];
let arr2 = ["A", "B", "C", "D"];
console.log([...arr1, ...arr2].sort((v2, v1)=>(v2.codePointAt(0) - v1.codePointAt(0) ? v2.codePointAt(0) - v1.codePointAt(0) : (v1.length - v2.length) || v2.codePointAt(1) - v1.codePointAt(1))));

@liuliangsir 解法是对的,就是你这个函数能不能换行啊,这样长看着多不舒服

情丝乱 2022-05-04 13:57:17

const arr1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
const arr2 = ['A', 'B', 'C', 'D']
const res = [].concat(...arr2.map(i => arr1.filter(j => j.startsWith(i)).concat(i)))
console.log(res)

小糖芽 2022-05-04 13:57:17
let arrA = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'];
let arrB = ['A', 'B', 'C', 'D',];
arrA.map(item => {
  if(item == arrB[0]+2) {return [item,arrB.shift()] } 
  else{return item}
}).flat()

借鉴了前面各位大神的。

花海 2022-05-04 13:57:16
const arr1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
const arr2 = ['A', 'B', 'C', 'D']
function combineArr(a1, a2) {
  const ret = a2.map((item, index) => {
    return [a1[index * 2], a1[index * 2 + 1], item]
  })
  return ret.toString().split(',')
}
console.log(combineArr(arr1, arr2))

2个参考点

  1. arr1和arr2本身就是有序的,A1的index和A的index成2倍关系
  2. 可以使用Array的toString方法将数组拍平
紫罗兰の梦幻 2022-05-04 13:57:16
const matchIndex = str => str.match(/d+/) || []
const getCharCode = str => str.match(/w/)[0].charCodeAt()
const result = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
  .concat(['A', 'B', 'C', 'D'])
  .sort((a,b) => {
    const [[aIndex = Infinity], [bIndex = Infinity]] = [matchIndex(a), matchIndex(b)]
    const [aChar, bChar] = [getCharCode(a), getCharCode(b)]
    return aChar === bChar
      ? aIndex - bIndex
      : aChar - bChar
  })
console.log(result)

提一个新思路的版本,从修改sort入手,不依赖数组下标,通用性更强

灯下孤影 2022-05-04 13:57:16
let arr1 = ["A1", "A2", "B1", "B2", "C1", "C2", "D1", "D2"]
  , arr2 = ["A", "B", "C", "D"]

function concatArr(arr1, arr2) {
  let newArr = []
  
  while (arr2.length !== 0) {
    let tag2 = arr2.pop()
    
    newArr.unshift(tag2)
    
    while (arr1.length !== 0) {
      let tag1 = arr1.pop()
      
      if (tag1.includes(tag2)) {
        newArr.unshift(tag1)
      } else {
        arr1.push(tag1)
        break
      }
    }
  }
  return newArr
}

console.log(arr1)
console.log(arr2)
console.log(concatArr(arr1, arr2))
治碍゛ 2022-05-04 13:57:16

其实解法很简单的

let arr1 = ["A1", "A2", "B1", "B2", "C1", "C2", "D1", "D2"];
let arr2 = ["A", "B", "C", "D"];
console.log(
  [...arr1, ...arr2]
    .sort(
      (v2, v1) => (
        v2.codePointAt(0) - v1.codePointAt(0) ||
        v1.length - v2.length ||
        v2.codePointAt(1) - v1.codePointAt(1)
      )
    )
);
南风起 2022-05-04 13:57:15

如果只是单纯解这道题的话,我这样做:

const res = ["A", "B", "C", "D"].reduce(
  (memo, item) => {
    const tmp = [...memo].reverse();
    const idx = memo.length - tmp.findIndex(i => i.startsWith(item)) - 1;

    return [...memo.slice(0, idx + 1), item, ...memo.slice(idx + 1)];
  },
  ["A1", "A2", "B1", "B2", "C1", "C2", "D1", "D2"]
);

这样即使是["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "D1", "D2"]等等也没问题啦

巡山小妖精 2022-05-04 13:57:14
const arr1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'];
const arr2 = ['A', 'B', 'C', 'D']
const arr = [...arr1,...arr2]
let targetArr = [];
arr2.forEach(item => {
  arr.forEach(ele=>{
      if(ele.includes(item)){
	targetArr.push(ele)
       }
   })
});	
console.log('targetArr',targetArr);
怀里藏娇 2022-05-04 13:57:13

我想问下,这题想考的是哪方面的知识?

假设有一种情况,让你在一个列表中插入一个广告,不光是数组,对象依然有这种需求,这道题其实就是平常经常需要用到的一个小功能。

一袭水袖舞倾城。 2022-05-04 13:54:40
var arr1 = ["A1", "A2", "B1", "B2", "C1", "C2", "D1", "D2"];
var arr2 = ["A", "B", "C", "D"];

arr2.forEach((it, index) => {
  arr1.splice((index + 1) * 2 + index, 0, it);
});

console.log(arr1);
荒路情人 2022-05-04 13:54:06
let arrA = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'];
let arrB = ['A', 'B', 'C', 'D',];
function combine(a, b) {
  while (b.length){
    let str =  b.shift();
    let indexNum = 0;
    a.forEach((item,index) => {
      if(item.indexOf(str) !== -1){
        indexNum = index
      }
    })
    a.splice(indexNum + 1, 0, str)
  }
  return a;
}
套路撩心 2022-05-04 13:50:18

我想问下,这题想考的是哪方面的知识?

征﹌骨岁月お 2022-05-04 13:50:18

var arrOne =["A1", "A2", "B1", "B2", "C1", "C2", "D1", "D2"];
var arrTwo = ['A', 'B', 'C', 'D'];

for (let i = 0; i < arrTwo.length; i++) {
let re = new RegExp(arrTwo[i], 'g');
for (let x = arrOne.length; x > 0; x--) {
if(re.test(arrOne[x])){
arrOne.splice(x+1,0,arrTwo[i])
}
}
}
console.log(arrOne);

这样是否可以呢?

世俗缘。▽ 2022-05-04 13:46:21

看一下我这个可以嘛

var a1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'];
var a2 =['A','B','C','D'];
var j=-1;
var arr=[]
for(let i=0;i<a1.length;i++){
    if(i%2 ===0){
	j++
	arr=arr.concat((a1.slice(i,i+2)).concat(a2[j]))
    }
}
console.log(arr)

——————————————————————
截图

时光瘦了。 2022-05-04 13:33:01

var arr1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2'];
var arr2 = ['A', 'B','C', 'D'];

function fn (arr1, arr2) {
let arr3 = [...arr1];
let index = -1;
arr2.forEach((v, i) => {
index = index + 3;
arr3.splice(index, 0, v);
});
return arr3;
}

console.log(fn(arr1, arr2)); // [ 'A1', 'A2', 'A', 'B1', 'B2', 'B', 'C1', 'C2', 'C', 'D1', 'D2', 'D' ]
// -1 + 3 = 2
// 2 + 3 = 5
// 5 + 3 = 8
// 8 + 3 = 11
// 首先想到了用concat+sort,但结果不对。后来想观察了一下,用splice插入,因为插入位置是固定的。

爺獨霸怡葒院 2022-05-04 10:27:50
var arr1 = ["A1", "A2", "B1", "B2", "C1", "C2", "D1", "D2"]
var arr2 = ["A", "B", "C", "D"]
var arr3 = arr1.concat(arr2);
arr3.sort().sort(function(a,b){
   if (a.charAt(0) == b.charAt(0) && a.length > b.length){
       return -1
   }
	
})```
请远离我﹫ 2022-05-04 05:49:28
let a1 =  ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
let a2 = ['A', 'B', 'C', 'D'].map((item) => {
  return item + 3
})

let a3 = [...a1, ...a2].sort().map((item) => {
  if(item.includes('3')){
    return item.split('')[0]
  }
  return item
})
删除→记忆 2022-05-03 21:45:32
var a = ['A1','A2','B1','B2','C1','C2','D1','D2']
var b = ['A','B','C','D']
// 对需要排序的数字和位置的临时存储
var mapped = a.concat(b).map(function(el, i) {
  return { index: i, value: /D$/.test(el) ? (el + 4) : el };
})
mapped.sort(function(a, b) {
  return +(a.value > b.value) || +(a.value === b.value) - 1;
});
var result = mapped.map(function(el){
  return a.concat(b)[el.index];
});

利用mdn对sort映射改善排序的方法进行的处理,不过对数组进行了多次处理,感觉方法不太好

旧时浪漫 2022-04-29 23:44:32
const arr1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
const arr2 = ['A', 'B', 'C', 'D']
const ret = []
let tmp = arr2[0]
let j = 0
for (let i=0;i<arr1.length;i++) {
  if (tmp === arr1[i].charAt(0)){
    ret.push(arr1[i])
  }else {
    ret.push(tmp)
    ret.push(arr1[i])
    tmp=arr2[++j]
  }
   if(i===arr1.length-1){
      ret.push(tmp)
    }
}
console.log(ret)
~没有更多了~

关于作者

0 文章
0 评论
23 人气
更多

推荐作者

lorenzathorton8

文章 0 评论 0

Zero

文章 0 评论 0

萧瑟寒风

文章 0 评论 0

mylayout

文章 0 评论 0

tkewei

文章 0 评论 0

17818769742

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文