vue实现数组拼接,保留同类型,删除原来的不同项,新增新的不同项

vue实现数组拼接,保留同类型,删除原来的不同项,新增新的不同项


需求:新数组合并到旧数组,要求保留原数组同类项并前移,不同项新增,内容都相同时不改变原数组

const testList = () => {
  let oldList: number[] = [1, 2, 3, 5], //旧数组
    newList: string[] = ['3', '2', '4', '6'], //新数组
    finallyList: any[] = [], //最终输出
    oldIndex: number[] = [], //旧数组中相同项索引
    newIndex: number[] = []; //新数组中相同项索引
  oldList.forEach((item: number, index: number) => {
    newList.forEach((items: string, indexes: number) => {
      if (item + '' === items) {
        oldIndex.push(index); //获取相同项索引
        newIndex.push(indexes);
      }
    });
  });
  newIndex.sort(); //新数组相同项索引升序排列
  if (oldList === newList) {
    finallyList = oldList; //原数组相同
  }
  if (oldIndex.length === oldList.length) {
    finallyList = oldList; //数组内容相同,位置不同
  }
  if (oldIndex.length === 0) {
    finallyList = newList; //无相同项
  }
  if (oldIndex.length > 0) {
    let oldToNew: number[] = [];
    oldIndex.forEach((item: number) => {
      oldToNew.push(oldList[item]); //取旧数组相同项
    });
    for (let i: number = newIndex.length - 1; i >= 0; i--) {
      newList.splice(newIndex[i], 1); //删除新数组相同项
    }
    finallyList = oldToNew.concat(newList); //合并
  }
  console.log(finallyList);
};

Number类型为原数组,String类型为新数组,这里采用两种不同类型只是为了更直观的看出来
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值