是否有一种方法可以在JavaScript中返回两个数组之间的差异?

例如:

var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];

// need ["c", "d"]

当前回答

如果你想找出两个object数组之间的差异,你可以这样做:

let arrObj = [{id: 1},{id: 2},{id: 3}] let arrObj2 = [{id: 1},{id: 3}] let result = arrObj。filter(x => arrObj2.)每个(x2 => x2。Id == x.id) console.log(结果)

其他回答

这是我用来获得两个数组之间的差异的函数-它适用于数值,字符串,混合num/字符串数组。在数组/多维数组中不是对象文字

function diff(arr1, arr2) {

    var x, 
        t;

    function uniq(a, b) {
        t = b;

        if( (b === 0 && x[b+1]!==a) || 
           (t > 0 && a !== x[b+1] && a !== x[b-1]) ) {
            return  a;
        }
    }


    x = arr1.concat(arr2).sort();

    return x.filter(uniq);
}

var a1 = ['a', 'b', 'e', 'c'],
    a2 = ['b', 'a', 'c', 'f' ];

diff(a1, a2);

数据:

var new_storage = JSON.parse('[{"id_order":"0003"},{"id_order":"0004"},{"id_order":"0006"}]');

var old_storage = JSON.parse('[{"id_order":"0001"},{"id_order":"0002"},{"id_order":"0003"},{"id_order":"0004"},{"id_order":"0005"}]');

使用过滤器:

var diff = new_storage
.filter(x => {if(!(old_storage.filter(y => y.id_order==x.id_order)).length){return x}})
    .concat(old_storage
    .filter(x => {if(!(new_storage.filter(y => y.id_order==x.id_order)).length){return x}})
                       ) 

console.log(JSON.stringify(diff))

两个数组的结果不同

[{"id_order":"0006"},{"id_order":"0001"},{"id_order":"0002"},{"id_order":"0005"}]
    function arrayDiff(a, b) {
      return a.concat(b).filter(val => !(b.includes(val)));
      //(or) return a.concat(b).filter(val => !(a.includes(val) && b.includes(val)));
    }

这是工作的:基本上合并两个数组,寻找重复的,并将没有重复的推入一个新数组,这是差异。

函数diff(arr1, arr2) { var newArr = []; Var arr = ar1 .concat(arr2); For (var I in arr){ Var f = arr[i]; Var t = 0; (j = 0;j < arr.length;j + +) { If (arr[j] === f){ t + +; } } 如果(t == 1){ newArr.push (f); } } 返回newArr; }

使用http://phrogz.net/JS/ArraySetMath.js你可以:

var array1 = ["test1", "test2","test3", "test4"];
var array2 = ["test1", "test2","test3","test4", "test5", "test6"];

var array3 = array2.subtract( array1 );
// ["test5", "test6"]

var array4 = array1.exclusion( array2 );
// ["test5", "test6"]