如何获得两个数组的并集[重复]

时间:2021-09-20 22:56:07

This question already has an answer here:

这个问题在这里已有答案:

Say I have two sets (arrays):

假设我有两组(数组):

a = [1,2,3];
b = [2,3,5];

and I want 1,2,3,5 out only.

我只想要1,2,3,5。

What is the most terse way to do this? Or, failing that, what is a way to do this?

最简洁的方法是什么?或者,如果不这样做,有什么方法可以做到这一点?

2 个解决方案

#1


0  

var a = [1,2,3];
var b = [2,3,5];

//Concat both arrays [1,2,3,2,3,5]
var result = a.concat(b).filter(function(value, index, self) { //array unique
    return self.indexOf(value) === index; 
});
console.log(result); //[1, 2, 3, 5];

#2


0  

The following post should help...about half way down is a union with a library reference.

以下帖子应该有帮助...大约一半是带库参考的联合。

How to merge two arrays in Javascript and de-duplicate items

如何在Javascript中合并两个数组并重复删除项目

#1


0  

var a = [1,2,3];
var b = [2,3,5];

//Concat both arrays [1,2,3,2,3,5]
var result = a.concat(b).filter(function(value, index, self) { //array unique
    return self.indexOf(value) === index; 
});
console.log(result); //[1, 2, 3, 5];

#2


0  

The following post should help...about half way down is a union with a library reference.

以下帖子应该有帮助...大约一半是带库参考的联合。

How to merge two arrays in Javascript and de-duplicate items

如何在Javascript中合并两个数组并重复删除项目