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类型为新数组,这里采用两种不同类型只是为了更直观的看出来