如何在JavaScript中获取两个数组之间的差异?

2022-08-29 22:04:59

有没有办法在JavaScript中返回两个数组之间的差异?

例如:

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

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

答案 1

有更好的使用ES7的方法:


路口

 let intersection = arr1.filter(x => arr2.includes(x));

Intersection difference Venn Diagram

因为它会产生.另一方面,for 将返回相同的东西。[1,2,3] [2,3][2,3][1,2,3] [2,3,5]


差异

let difference = arr1.filter(x => !arr2.includes(x));

Right difference Venn Diagram

因为它会产生.另一方面,for 将返回相同的东西。[1,2,3] [2,3][1][1,2,3] [2,3,5]


对于对称差,您可以执行以下操作:

let difference = arr1
                 .filter(x => !arr2.includes(x))
                 .concat(arr2.filter(x => !arr1.includes(x)));

Symmetric difference Venn Diagram

这样,您将获得一个数组,其中包含arr1中不在arr2中的所有元素,反之亦然

正如@Joshaven Potter在他的答案中指出的那样,你可以将其添加到Array.prototype中,这样它就可以这样使用:

Array.prototype.diff = function(arr2) { return this.filter(x => !arr2.includes(x)); }
[1, 2, 3].diff([2, 3])

答案 2

Array.prototype.diff = function(a) {
    return this.filter(function(i) {return a.indexOf(i) < 0;});
};

//////////////
// Examples //
//////////////

const dif1 = [1,2,3,4,5,6].diff( [3,4,5] );  
console.log(dif1); // => [1, 2, 6]


const dif2 = ["test1", "test2","test3","test4","test5","test6"].diff(["test1","test2","test3","test4"]);  
console.log(dif2); // => ["test5", "test6"]

注意,在 IE9 之前不可用。.indexOf().filter()