在 JavaScript 中获取两个数组的并集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3629817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting a union of two arrays in JavaScript
提问by CFNinja
Say I have an array of [34, 35, 45, 48, 49]and another array of [48, 55]. How can I get a resulting array of [34, 35, 45, 48, 49, 55]?
假设我有一个数组[34, 35, 45, 48, 49]和另一个数组[48, 55]. 我怎样才能得到一个结果数组[34, 35, 45, 48, 49, 55]?
采纳答案by kennytm
If you don't need to keep the order, and consider 45and "45"to be the same:
如果你不需要保持顺序,并且考虑45和"45"是一样的:
function union_arrays (x, y) {
var obj = {};
for (var i = x.length-1; i >= 0; -- i)
obj[x[i]] = x[i];
for (var i = y.length-1; i >= 0; -- i)
obj[y[i]] = y[i];
var res = []
for (var k in obj) {
if (obj.hasOwnProperty(k)) // <-- optional
res.push(obj[k]);
}
return res;
}
console.log(union_arrays([34,35,45,48,49], [44,55]));
回答by Salvador Dali
With the arrival of ES6 with sets and splat operator (at the time of being works only in Firefox, check compatibility table), you can write the following cryptic one liner:
随着带有集合和 splat 运算符的 ES6 的到来(当时仅适用于 Firefox,请查看兼容性表),您可以编写以下神秘的一行代码:
var a = [34, 35, 45, 48, 49];
var b = [48, 55];
var union = [...new Set([...a, ...b])];
console.log(union);
Little explanation about this line: [...a, ...b]concatenates two arrays, you can use a.concat(b)as well. new Set()create a set out of it and thus your union. And the last [...x]converts it back to an array.
关于这一行的小解释:[...a, ...b]连接两个数组,你也可以使用a.concat(b)。new Set()从中创建一个集合,从而创建您的工会。最后[...x]将其转换回数组。
回答by Codler
If you use the library underscoreyou can write like this
如果你使用库下划线,你可以这样写
var unionArr = _.union([34,35,45,48,49], [48,55]);
console.log(unionArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
回答by Gareth Farrington
I'm probably wasting time on a dead thread here. I just had to implement this and went looking to see if I was wasting my time.
我可能在这里的死线程上浪费时间。我只需要实现这一点,然后去看看我是否在浪费时间。
I really like KennyTM's answer. That's just how I would attack the problem. Merge the keys into a hash to naturally eliminate duplicates and then extract the keys. If you actually have jQuery you can leverage its goodies to make this a 2 line problem and then roll it into an extension. The each() in jQuery will take care of not iterating over items where hasOwnProperty() is false.
我真的很喜欢 KennyTM 的回答。这就是我将如何解决问题。将键合并成一个散列以自然地消除重复项,然后提取键。如果你真的有 jQuery,你可以利用它的优点把它变成一个 2 行问题,然后把它变成一个扩展。jQuery 中的 each() 将负责不迭代 hasOwnProperty() 为 false 的项目。
jQuery.fn.extend({
union: function(array1, array2) {
var hash = {}, union = [];
$.each($.merge($.merge([], array1), array2), function (index, value) { hash[value] = value; });
$.each(hash, function (key, value) { union.push(key); } );
return union;
}
});
Note that both of the original arrays are left intact. Then you call it like this:
请注意,两个原始数组都保持不变。然后你这样称呼它:
var union = $.union(array1, array2);
回答by Bob
function unique(arrayName)
{
var newArray=new Array();
label: for(var i=0; i<arrayName.length;i++ )
{
for(var j=0; j<newArray.length;j++ )
{
if(newArray[j]==arrayName[i])
continue label;
}
newArray[newArray.length] = arrayName[i];
}
return newArray;
}
var arr1 = new Array(0,2,4,4,4,4,4,5,5,6,6,6,7,7,8,9,5,1,2,3,0);
var arr2= new Array(3,5,8,1,2,32,1,2,1,2,4,7,8,9,1,2,1,2,3,4,5);
var union = unique(arr1.concat(arr2));
console.log(union);
回答by Adam Fox
Adapted from: https://stackoverflow.com/a/4026828/1830259
改编自:https: //stackoverflow.com/a/4026828/1830259
Array.prototype.union = function(a)
{
var r = this.slice(0);
a.forEach(function(i) { if (r.indexOf(i) < 0) r.push(i); });
return r;
};
Array.prototype.diff = function(a)
{
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
var s1 = [1, 2, 3, 4];
var s2 = [3, 4, 5, 6];
console.log("s1: " + s1);
console.log("s2: " + s2);
console.log("s1.union(s2): " + s1.union(s2));
console.log("s2.union(s1): " + s2.union(s1));
console.log("s1.diff(s2): " + s1.diff(s2));
console.log("s2.diff(s1): " + s2.diff(s1));
// Output:
// s1: 1,2,3,4
// s2: 3,4,5,6
// s1.union(s2): 1,2,3,4,5,6
// s2.union(s1): 3,4,5,6,1,2
// s1.diff(s2): 1,2
// s2.diff(s1): 5,6
回答by Narendra Manam
If you wants to concatenate two arrays without any duplicate value,Just try this
如果你想连接两个没有任何重复值的数组,试试这个
var a=[34, 35, 45, 48, 49];
var b=[48, 55];
var c=a.concat(b).sort();
var res=c.filter((value,pos) => {return c.indexOf(value) == pos;} );
回答by Warbo
I like Peter Ajtai's concat-then-unique solution, but the code's not very clear. Here's a nicer alternative:
我喜欢 Peter Ajtai 的 concat-then-unique 解决方案,但代码不是很清楚。这是一个更好的选择:
function unique(x) {
return x.filter(function(elem, index) { return x.indexOf(elem) === index; });
};
function union(x, y) {
return unique(x.concat(y));
};
Since indexOf returns the index of the firstoccurence, we check this against the current element's index (the second parameter to the filter predicate).
由于 indexOf 返回第一次出现的索引,我们根据当前元素的索引(过滤谓词的第二个参数)检查它。
回答by Kristian Abrahamsen
You can use a jQuery plugin: jQuery Array Utilities
您可以使用 jQuery 插件:jQuery Array Utilities
For example the code below
例如下面的代码
$.union([1, 2, 2, 3], [2, 3, 4, 5, 5])
will return [1,2,3,4,5]
将返回 [1,2,3,4,5]
回答by alejandro
function unionArray(arrayA, arrayB) {
var obj = {},
i = arrayA.length,
j = arrayB.length,
newArray = [];
while (i--) {
if (!(arrayA[i] in obj)) {
obj[arrayA[i]] = true;
newArray.push(arrayA[i]);
}
}
while (j--) {
if (!(arrayB[j] in obj)) {
obj[arrayB[j]] = true;
newArray.push(arrayB[j]);
}
}
return newArray;
}
var unionArr = unionArray([34, 35, 45, 48, 49], [44, 55]);
console.log(unionArr);

