javascript - 数组合并问题?

 

问题描述:

a=[78,187,30]
b=[78,186,185,25,30]
c=[78,187,186,185,25,30] //想获得的结果

a=[1,2,3,4,5]
b=[1,6,7,8,3,9,5]
c=[1,2,6,7,8,3,4,9,5] //想获得的结果

a、b数组里面的值都是唯一的,怎么用js获得想要的值呢?

问了ChatGPT都没解决,它给的方法在控制台输出结果不一致,因为chatGPT的js环境不一样。


 

第 1 个答案:

解决方法:

function mergeArrays(a, b, c) {
      let result = []
      for (let i = 0; i < b.length - 1; i++) {
        const start = b[i],
          end = b[i + 1]
        result.push(start)
        result = result.concat(a.slice(a.indexOf(start), a.indexOf(end)))
        result = result.concat(c.slice(c.indexOf(start), c.indexOf(end) + 1))
      }
      return [...new Set(result)]
    }
var a =[78,187,30]
var b=[78,30] //a和b共用的数值
var c=[78,186,185,25,30]

var a2=[1,2,3,4,5]
var b2=[1,3,5] //a2和b2共用的数值
var c2=[1,6,7,8,3,9,5]

console.log(mergeArrays(a,b,c))
console.log(mergeArrays(a2,b2,c2))

image.png


 

第 2 个答案:

function mergeArrays(a, b, c) {
    let result = [];
    for (let i = 0; i < b.length; i++) {
        while (a[0] !== b[i]) {
            result.push(a.shift());
        }
        while (c[0] !== b[i]) {
            result.push(c.shift());
        }
        result.push(b[i]);
        a.shift();
        c.shift();
    }
    result = [...result, ...a, ...c];
    return result;
}

let a = [1,2,3,4,5];
let b = [1,3,5];
let c = [1,6,7,8,3,9,5];

console.log(mergeArrays(a, b, c)); // 输出: [1,2,6,7,8,3,4,9,5]

企业微信截图_1688525106570.png


 

第 3 个答案:

image.png


 

第 4 个答案:

var a=[78,187,30]
var b=[78,186,185,25,30]
a=[1,2,3,4,5]
b=[1,6,7,8,3,9,5]
let s = new Set();
let exchange = 0;

function judgeFun(arr1, arr2) {
    for (let i=0; i<arr1.length; i++) {
        if (!s.has(arr1[i])) {
            if (arr2.includes(arr1[i])) {
                s.add(arr1[i]);
                if (exchange % 2 !== 0) {
                    exchange+=1;
                    judgeFun(arr2.slice(arr2.indexOf(arr1[i])), arr1.slice(i));
                }
            } else {
                s.add(arr1[i]);
                if (exchange % 2 === 0) {
                    exchange+=1;
                    judgeFun(arr2.slice(i), arr1.slice(i));
                }
            }
        }
    }
}

judgeFun(a, b);
console.log(Array.from(s));

现在有2个项目,项目A是主要业务代码,项目B是一个插件,2个都是vue项目,在开发阶段,有什么方法可以将2个项目合到一起开发。目前的开发步骤是在项目A中发现问题,需要拷贝相关数据到项目B中去, ...