如何在JavaScript和非重复项中合并两个数组?

时间:2021-10-17 12:14:05

I have two JavaScript arrays:

我有两个JavaScript数组:

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];

I want the output to be:

我希望输出为:

var array3 = ["Vijendra","Singh","Shakya"];

The output array should have repeated words removed.

输出数组应该重复删除。

How do I merge two arrays in JavaScript so that I get only the unique items from each array in the same order they were inserted into the original arrays?

如何将两个数组合并到JavaScript中,这样我就可以从每个数组中得到唯一的项,并将它们插入到原始数组中?

57 个解决方案

#1


1162  

To just merge the arrays (without removing duplicates)

只需合并数组(不删除重复项)

ES5 version use Array.concat:

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];

var array3 = array1.concat(array2); // Merges both arrays
// [ 'Vijendra', 'Singh', 'Singh', 'Shakya' ]

ES6 version use destructuring

const array1 = ["Vijendra","Singh"];
const array2 = ["Singh", "Shakya"];
const array3 = [...array1, ...array2];

Since there is no 'built in' way to remove duplicates (ECMA-262 actually has Array.forEach which would be great for this), we have to do it manually:

因为没有“内置”删除重复的方法(ECMA-262实际上有数组)。对于每个人来说,这都是很好的选择,我们必须手动去做:

Array.prototype.unique = function() {
    var a = this.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }

    return a;
};

Then, to use it:

然后,使用它:

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
// Merges both arrays and gets unique items
var array3 = array1.concat(array2).unique(); 

This will also preserve the order of the arrays (i.e, no sorting needed).

这也将保留数组的顺序(i。e,不需要排序)。

Since many people are annoyed about prototype augmentation of Array.prototype and for in loops, here is a less invasive way to use it:

由于许多人对阵列的原型增加感到恼火。原型和在循环中,这是一种侵入性较低的使用方法:

function arrayUnique(array) {
    var a = array.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }

    return a;
}

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
    // Merges both arrays and gets unique items
var array3 = arrayUnique(array1.concat(array2));

For those who are fortunate enough to work with browsers where ES5 is available, you can use Object.defineProperty like this:

对于那些有幸能够在ES5可用的浏览器中工作的人,可以使用Object.defineProperty:

Object.defineProperty(Array.prototype, 'unique', {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function() {
        var a = this.concat();
        for(var i=0; i<a.length; ++i) {
            for(var j=i+1; j<a.length; ++j) {
                if(a[i] === a[j])
                    a.splice(j--, 1);
            }
        }

        return a;
    }
});

#2


492  

With Underscore.js or Lo-Dash you can do:

与强调。js或Lo-Dash:

_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]

http://underscorejs.org/#union

http://underscorejs.org/联盟

http://lodash.com/docs#union

http://lodash.com/docs联盟

#3


175  

First concatenate the two arrays, next filter out only the unique items.

首先连接两个数组,然后只过滤出唯一的项。

var a = [1, 2, 3], b = [101, 2, 1, 10];
var c = a.concat(b);
var d = c.filter(function (item, pos) {return c.indexOf(item) == pos});

// d is [1,2,3,101,10]

http://jsfiddle.net/simo/98622/

http://jsfiddle.net/simo/98622/

Edit

As suggested by @Dmitry (see the second comment below) a more performance wise solution would be to filter out the unique items in b before concatenating with a

正如@Dmitry所建议的(请参阅下面的第二条评论),一个更高效的解决方案是在连接a之前过滤掉b中的唯一项。

var a = [1, 2, 3], b = [101, 2, 1, 10];
var c = a.concat(b.filter(function (item) {
    return a.indexOf(item) < 0;
}));

// d is [1,2,3,101,10]

#4


100  

This is an ECMAScript 6 solution using spread operator and array generics.

这是一个使用扩展操作符和数组泛型的ECMAScript 6解决方案。

Currently it only works with Firefox, and possibly Internet Explorer Technical Preview.

目前它只适用于Firefox,也可能是Internet Explorer技术预览版。

But if you use Babel, you can have it now.

但是如果你使用巴别,你现在就可以拥有它。

// Input: [ [1, 2, 3], [101, 2, 1, 10], [2, 1] ]
// Output: [1, 2, 3, 101, 10]
function mergeDedupe(arr)
{
  return [...new Set([].concat(...arr))];
}

#5


76  

ES6

array1.push(...array2) // => don't remove duplication 

OR

[...array1,...array2] //   =>  don't remove duplication 

OR

[...new Set([...array1 ,...array2])]; //   => remove duplication

#6


31  

Here is a slightly different take on the loop. With some of the optimizations in the latest version of Chrome, it is the fastest method for resolving the union of the two arrays (Chrome 38.0.2111).

这里有一个稍微不同的循环。在最新版本的Chrome中有一些优化,这是解决两个数组的联合的最快方法(Chrome 38.0.2111)。

http://jsperf.com/merge-two-arrays-keeping-only-unique-values

http://jsperf.com/merge-two-arrays-keeping-only-unique-values

var array1 = ["Vijendra", "Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = [];

var arr = array1.concat(array2),
  len = arr.length;

while (len--) {
  var itm = arr[len];
  if (array3.indexOf(itm) === -1) {
    array3.unshift(itm);
  }
}

while loop: ~589k ops/s
filter: ~445k ops/s
lodash: 308k ops/s
for loops: 225k ops/s

while循环:~589k ops/s filter: ~445k ops/s lodash: 308k ops/s for循环:225k ops/s。

A comment pointed out that one of my setup variables was causing my loop to pull ahead of the rest, because it didn't have to initialize an empty array to write to. I agree with that, so I've rewritten the test to even the playing field, and included an even faster option.

有一条评论指出,我的一个设置变量导致我的循环先于其他的,因为它不需要初始化一个空的数组来写。我同意这一点,所以我重写了测试,甚至包括了游戏领域,并且包含了一个更快的选项。

http://jsperf.com/merge-two-arrays-keeping-only-unique-values/21

http://jsperf.com/merge-two-arrays-keeping-only-unique-values/21

var whileLoopAlt = function(array1, array2) {
    var array3 = [];
    var arr = array1.concat(array2);
    var len = arr.length;
    var assoc = {};

    while(len--) {
        var itm = arr[len];

        if(!assoc[itm]) { // Eliminate the indexOf call
            array3.unshift(itm);
            assoc[itm] = true;
        }
    }

    return array3;
};

In this alternate solution, I've combined one answer's associative array solution to eliminate the .indexOf() call in the loop which was slowing things down a lot with a second loop, and included some of the other optimizations that other users have suggested in their answers as well.

在这个替代的解决方案中,我结合了一个答案的关联数组解决方案,以消除循环中的. indexof()调用,该方法通过第二个循环来降低很多东西的速度,并包含了其他用户在回答中所建议的其他一些优化。

The top answer here with the double loop on every value (i-1) is still significantly slower. lodash is still doing strong, and I still would recommend it to anyone who doesn't mind adding a library to their project. For those who don't want to, my while loop is still a good answer and the filter answer has a very strong showing here, beating out all on my tests with the latest Canary Chrome (44.0.2360) as of this writing.

在这里,对于每个值(i-1)的双循环的最上面的答案仍然要慢得多。lodash仍然很强大,我仍然会向任何不介意在项目中添加一个库的人推荐它。对于那些不想这样做的人来说,我的while循环仍然是一个很好的答案,这个过滤器的答案在这里有很强的显示效果,在我的测试中,我用最新的Canary Chrome(44.0.2360)进行了测试。

Check out Mike's answer and Dan Stocker's answer if you want to step it up a notch in speed. Those are by far the fastest of all results after going through almost all of the viable answers.

如果你想加快速度的话,看看麦克的答案和丹·斯托克的回答。到目前为止,这些都是经过几乎所有可行的答案后最快的结果。

#7


25  

You can do it simply with ECMAScript 6,

你可以简单地用ECMAScript 6来做,

var array1 = ["Vijendra", "Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = [...new Set([...array1 ,...array2])];
console.log(array3); // ["Vijendra", "Singh", "Shakya"];
  • Use the spread operator for concatenating the array.
  • 使用扩展操作符来连接数组。
  • Use Set for creating a distinct set of elements.
  • 用于创建一组不同元素的集合。
  • Again use the spread operator to convert the Set into an array.
  • 再次使用扩展操作符将集合转换为数组。

#8


16  

Using a Set (ECMAScript 2015), it will be as simple as that:

使用一个Set (ECMAScript 2015),它将非常简单:

const array1 = ["Vijendra", "Singh"];
const array2 = ["Singh", "Shakya"];
const array3 = Array.from(new Set(array1.concat(array2)));

#9


14  

Array.prototype.merge = function(/* variable number of arrays */){
    for(var i = 0; i < arguments.length; i++){
        var array = arguments[i];
        for(var j = 0; j < array.length; j++){
            if(this.indexOf(array[j]) === -1) {
                this.push(array[j]);
            }
        }
    }
    return this;
};

A much better array merge function.

一个更好的数组合并函数。

#10


13  

Just throwing in my two cents.

只是扔了我两美分。

function mergeStringArrays(a, b){
    var hash = {};
    var ret = [];

    for(var i=0; i < a.length; i++){
        var e = a[i];
        if (!hash[e]){
            hash[e] = true;
            ret.push(e);
        }
    }

    for(var i=0; i < b.length; i++){
        var e = b[i];
        if (!hash[e]){
            hash[e] = true;
            ret.push(e);
        }
    }

    return ret;
}

This is a method I use a lot, it uses an object as a hashlookup table to do the duplicate checking. Assuming that the hash is O(1), then this runs in O(n) where n is a.length + b.length. I honestly have no idea how the browser does the hash, but it performs well on many thousands of data points.

这是一个我经常使用的方法,它使用一个对象作为hashlookup表来执行重复检查。假设哈希是O(1),那么这是在O(n)中,其中n是a。+ b.length长度。老实说,我不知道浏览器是如何处理散列的,但它在成千上万个数据点上执行得很好。

#11


13  

Why don't you use an object? It looks like you're trying to model a set. This won't preserve the order, however.

为什么不用对象呢?看起来你是在尝试建立一个集合,但这不会维持秩序。

var set1 = {"Vijendra":true, "Singh":true}
var set2 = {"Singh":true,  "Shakya":true}

// Merge second object into first
function merge(set1, set2){
  for (var key in set2){
    if (set2.hasOwnProperty(key))
      set1[key] = set2[key]
  }
  return set1
}

merge(set1, set2)

// Create set from array
function setify(array){
  var result = {}
  for (var item in array){
    if (array.hasOwnProperty(item))
      result[array[item]] = true
  }
  return result
}

#12


11  

Just steer clear of nested loops (O(n^2)), and .indexOf() (+O(n)).

只是避开嵌套循环(O(n ^ 2)),和.indexOf()(+ O(n))。

function merge(a, b) {
    var hash = {}, i;
    for (i=0; i<a.length; i++) {
        hash[a[i]]=true;
    } 
    for (i=0; i<b.length; i++) {
        hash[b[i]]=true;
    } 
    return Object.keys(hash);
}

#13


8  

My one and a half penny:

我的一个半便士:

Array.prototype.concat_n_dedupe = function(other_array) {
  return this
    .concat(other_array) // add second
    .reduce(function(uniques, item) { // dedupe all
      if (uniques.indexOf(item) == -1) {
        uniques.push(item);
      }
      return uniques;
    }, []);
};

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];

var result = array1.concat_n_dedupe(array2);

console.log(result);

#14


6  

//Array.indexOf was introduced in javascript 1.6 (ECMA-262) 
//We need to implement it explicitly for other browsers, 
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt, from)
  {
    var len = this.length >>> 0;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}
//now, on to the problem

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];

var merged = array1.concat(array2);
var t;
for(i = 0; i < merged.length; i++)
  if((t = merged.indexOf(i + 1, merged[i])) != -1)
  {
    merged.splice(t, 1);
    i--;//in case of multiple occurrences
  }

Implementation of indexOf method for other browsers is taken from MDC

其他浏览器的indexOf方法的实现是从MDC中获得的。

#15


6  

Simplified simo's answer and turned it into a nice function.

简化了simo的答案,并把它变成了一个很好的函数。

function mergeUnique(arr1, arr2){
    return arr1.concat(arr2.filter(function (item) {
        return arr1.indexOf(item) === -1;
    }));
}

#16


5  

Array.prototype.add = function(b){
    var a = this.concat();                // clone current object
    if(!b.push || !b.length) return a;    // if b is not an array, or empty, then return a unchanged
    if(!a.length) return b.concat();      // if original is empty, return b

    // go through all the elements of b
    for(var i = 0; i < b.length; i++){
        // if b's value is not in a, then add it
        if(a.indexOf(b[i]) == -1) a.push(b[i]);
    }
    return a;
}

// Example:
console.log([1,2,3].add([3, 4, 5])); // will output [1, 2, 3, 4, 5]

#17


5  

The best solution...

最好的解决方案……

You can check directly in the browser console by hitting...

你可以通过点击来直接查看浏览器控制台。

Without duplicate

a = [1, 2, 3];
b = [3, 2, 1, "prince"];

a.concat(b.filter(function(el) {
    return a.indexOf(el) === -1;
}));

With duplicate

["prince", "asish", 5].concat(["ravi", 4])

If you want without duplicate you can try a better solution from here - Shouting Code.

如果你不想复制,你可以从这里尝试一个更好的解决方案——大喊代码。

[1, 2, 3].concat([3, 2, 1, "prince"].filter(function(el) {
    return [1, 2, 3].indexOf(el) === -1;
}));

Try on Chrome browser console

尝试Chrome浏览器控制台。

 f12 > console

Output:

输出:

["prince", "asish", 5, "ravi", 4]

[1, 2, 3, "prince"]

#18


4  

You can achieve it simply using Underscore.js's => uniq:

您可以简单地使用下划线实现它。js = > uniq:

array3 = _.uniq(array1.concat(array2))

console.log(array3)

It will print ["Vijendra", "Singh", "Shakya"].

它将印刷["Vijendra", "Singh", "Shakya"]。

#19


3  

New solution ( which uses Array.prototype.indexOf and Array.prototype.concat ):

新解决方案(使用Array.prototype)。indexOf和Array.prototype。concat):

Array.prototype.uniqueMerge = function( a ) {
    for ( var nonDuplicates = [], i = 0, l = a.length; i<l; ++i ) {
        if ( this.indexOf( a[i] ) === -1 ) {
            nonDuplicates.push( a[i] );
        }
    }
    return this.concat( nonDuplicates )
};

Usage:

用法:

>>> ['Vijendra', 'Singh'].uniqueMerge(['Singh', 'Shakya'])
["Vijendra", "Singh", "Shakya"]

Array.prototype.indexOf ( for internet explorer ):

Array.prototype。indexOf (internet explorer):

Array.prototype.indexOf = Array.prototype.indexOf || function(elt)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0) ? Math.ceil(from): Math.floor(from); 
    if (from < 0)from += len;

    for (; from < len; from++)
    {
      if (from in this && this[from] === elt)return from;
    }
    return -1;
  };

#20


2  

In Dojo 1.6+

在Dojo 1.6 +

var unique = []; 
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = array1.concat(array2); // Merged both arrays

dojo.forEach(array3, function(item) {
    if (dojo.indexOf(unique, item) > -1) return;
    unique.push(item); 
});

Update

更新

See working code.

看到工作代码。

http://jsfiddle.net/UAxJa/1/

http://jsfiddle.net/UAxJa/1/

#21


2  

Merge an unlimited number of arrays or non-arrays and keep it unique:

合并无限数量的数组或非数组,并保持它唯一:

function flatMerge() {
    return Array.prototype.reduce.call(arguments, function (result, current) {
        if (!(current instanceof Array)) {
            if (result.indexOf(current) === -1) {
                result.push(current);
            }
        } else {
            current.forEach(function (value) {
                console.log(value);
                if (result.indexOf(value) === -1) {
                    result.push(value);
                }
            });
        }
        return result;
    }, []);
}

flatMerge([1,2,3], 4, 4, [3, 2, 1, 5], [7, 6, 8, 9], 5, [4], 2, [3, 2, 5]);
// [1, 2, 3, 4, 5, 7, 6, 8, 9]

flatMerge([1,2,3], [3, 2, 1, 5], [7, 6, 8, 9]);
// [1, 2, 3, 5, 7, 6, 8, 9]

flatMerge(1, 3, 5, 7);
// [1, 3, 5, 7]

#22


2  

Assuming original arrays don't need de-duplication, this should be pretty fast, retain original order, and does not modify the original arrays...

假设原始数组不需要去复制,这应该是非常快的,保留原始的顺序,并且不修改原始数组…

function arrayMerge(base, addendum){
    var out = [].concat(base);
    for(var i=0,len=addendum.length;i<len;i++){
        if(base.indexOf(addendum[i])<0){
            out.push(addendum[i]);
        }
    }
    return out;
}

usage:

用法:

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = arrayMerge(array1, array2);

console.log(array3);
//-> [ 'Vijendra', 'Singh', 'Shakya' ]

#23


2  

A functional approach with ES2015

Following the functional approach a union of two Arrays is just the composition of concat and filter. In order to provide optimal performance we resort to the native Set data type, which is optimized for property lookups.

在函数方法之后,两个数组的结合就是concat和filter的组合。为了提供最优的性能,我们采用了本机集数据类型,这是针对属性查找优化的。

Anyway, the key question in conjunction with a union function is how to treat duplicates. The following permutations are possible:

总之,结合一个联合函数的关键问题是如何处理重复。以下排列是可能的:

Array A      + Array B

[unique]     + [unique]
[duplicated] + [unique]
[unique]     + [duplicated]
[duplicated] + [duplicated]

The first two permutations are easy to handle with a single function. However, the last two are more complicated, since you can't process them as long as you rely on Set lookups. Since switching to plain old Object property lookups would entail a serious performance hit the following implementation just ignores the third and fourth permutation. You would have to build a separate version of union to support them.

前两个排列很容易处理单个函数。但是,最后两个比较复杂,因为只要依赖设置查找,就无法处理它们。由于切换到普通的旧对象属性查找会导致严重的性能损失,所以下面的实现只会忽略第三和第四个排列。你必须建立一个独立的联盟来支持他们。


// small, reusable auxiliary functions

const comp = f => g => x => f(g(x));
const apply = f => a => f(a);
const flip = f => b => a => f(a) (b);
const concat = xs => y => xs.concat(y);
const afrom = apply(Array.from);
const createSet = xs => new Set(xs);
const filter = f => xs => xs.filter(apply(f));


// de-duplication

const dedupe = comp(afrom) (createSet);


// the actual union function

const union = xs => ys => {
  const zs = createSet(xs);  
  return concat(xs) (
    filter(x => zs.has(x)
     ? false
     : zs.add(x)
  ) (ys));
}


// mock data

const xs = [1,2,2,3,4,5];
const ys = [0,1,2,3,3,4,5,6,6];


// here we go

console.log( "unique/unique", union(dedupe(xs)) (ys) );
console.log( "duplicated/unique", union(xs) (ys) );

From here on it gets trivial to implement an unionn function, which accepts any number of arrays (inspired by naomik's comments):

从这里开始,实现一个unionn函数变得很简单,该函数接受任意数量的数组(受naomik的注释启发):

// small, reusable auxiliary functions

const uncurry = f => (a, b) => f(a) (b);
const foldl = f => acc => xs => xs.reduce(uncurry(f), acc);

const apply = f => a => f(a);
const flip = f => b => a => f(a) (b);
const concat = xs => y => xs.concat(y);
const createSet = xs => new Set(xs);
const filter = f => xs => xs.filter(apply(f));


// union and unionn

const union = xs => ys => {
  const zs = createSet(xs);  
  return concat(xs) (
    filter(x => zs.has(x)
     ? false
     : zs.add(x)
  ) (ys));
}

const unionn = (head, ...tail) => foldl(union) (head) (tail);


// mock data

const xs = [1,2,2,3,4,5];
const ys = [0,1,2,3,3,4,5,6,6];
const zs = [0,1,2,3,4,5,6,7,8,9];


// here we go

console.log( unionn(xs, ys, zs) );

It turns out unionn is just foldl (aka Array.prototype.reduce), which takes union as its reducer. Note: Since the implementation doesn't use an additional accumulator, it will throw an error when you apply it without arguments.

结果表明,unionn只是foldl(即Array.prototype.reduce),它将union作为它的减速器。注意:由于实现不使用额外的累加器,所以当您不使用参数的时候,它会抛出一个错误。

#24


2  

The easiest way to do this is either to use concat() to merge the arrays and then use filter() to remove the duplicates, or to use concat() and then put the merged array inside a Set().

最简单的方法是使用concat()合并数组,然后使用filter()来删除重复项,或者使用concat(),然后将合并的数组放入Set()中。

First way:

第一个方法:

const firstArray = [1,2, 2];
const secondArray = [3,4];
// now lets merge them
const mergedArray = firstArray.concat(secondArray); // [1,2,2,3,4]
//now use filter to remove dups
const removeDuplicates = mergedArray.filter((elem, index) =>  mergedArray.indexOf(elem) === index); // [1,2,3, 4]

Second way (but with performance implications on the UI):

第二种方法(但对UI的性能影响):

const firstArray = [1,2, 2];
const secondArray = [3,4];
// now lets merge them
const mergedArray = firstArray.concat(secondArray); // [1,2,2,3,4]
const removeDuplicates = new Set(mergedArray);

#25


2  

The best and simplest way to do that is using the function "some()" of JavaScript that returns true or false indicating if the array contains the object's element. You can make this:

最好最简单的方法是使用函数“some()”来返回true或false,表示数组是否包含对象元素。你可以这样:

var array1 = ["Vijendra","Singh"]; 
var array2 = ["Singh", "Shakya"];

var array3 = array1;

array2.forEach(function(elementArray2){
    var isEquals = array1.some(function(elementArray1){
        return elementArray1 === elementArray2;
    })
    if(!isEquals){
        array3.push(elementArray2);
    }
});
console.log(array3);

The results:

结果:

["Vijendra", "Singh", "Shakya"]

ss you wish... without duplicate it...

党*你希望……没有重复的…

#26


2  

looks like the accepted answer is the slowest in my tests;

看起来接受的答案是我测试中最慢的。

note I am merging 2 arrays of objects by Key

注意,我正在合并两个对象数组。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<button type='button' onclick='doit()'>do it</button>
<script>
function doit(){
    var items = [];
    var items2 = [];
    var itemskeys = {};
    for(var i = 0; i < 10000; i++){
        items.push({K:i, C:"123"});
        itemskeys[i] = i;
    }

    for(var i = 9000; i < 11000; i++){
        items2.push({K:i, C:"123"});
    }

    console.time('merge');
    var res = items.slice(0);

    //method1();
    method0();
    //method2();

    console.log(res.length);
    console.timeEnd('merge');

    function method0(){
        for(var i = 0; i < items2.length; i++){
            var isok = 1;
            var k = items2[i].K;
            if(itemskeys[k] == null){
                itemskeys[i] = res.length;
                res.push(items2[i]);
            }
        }
    }

    function method1(){
        for(var i = 0; i < items2.length; i++){
            var isok = 1;
            var k = items2[i].K;

            for(var j = 0; j < items.length; j++){
                if(items[j].K == k){
                    isok = 0;
                    break;
                }
            }

            if(isok) res.push(items2[i]);
        }  
    }

    function method2(){
        res = res.concat(items2);
        for(var i = 0; i < res.length; ++i) {
            for(var j = i+1; j < res.length; ++j) {
                if(res[i].K === res[j].K)
                    res.splice(j--, 1);
            }
        }
    }
}
</script>
</body>
</html>

#27


1  

var MergeArrays=function(arrayOne, arrayTwo, equalityField) {
    var mergeDictionary = {};

    for (var i = 0; i < arrayOne.length; i++) {
        mergeDictionary[arrayOne[i][equalityField]] = arrayOne[i];
    }

    for (var i = 0; i < arrayTwo.length; i++) {
        mergeDictionary[arrayTwo[i][equalityField]] = arrayTwo[i];
    }

    return $.map(mergeDictionary, function (value, key) { return value });
}

Leveraging dictionaries and Jquery you could merge the two arrays and not get duplicates. In my example I'm using a given field on the object but could be just the object itself.

利用词典和Jquery可以合并这两个数组,而不是复制。在我的例子中,我在对象上使用给定的字段,但可能只是对象本身。

#28


1  

Another approach for your review with reduce func:

另一种减少func的方法是:

function mergeDistinct(arResult, candidate){
  if (-1 == arResult.indexOf(candidate)) {
    arResult.push(candidate);
  }
  return arResult;
}

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];

var arMerge = [];
arMerge = array1.reduce(mergeDistinct, arMerge);
arMerge = array2.reduce(mergeDistinct, arMerge);//["Vijendra","Singh","Shakya"];

#29


1  

If you want to check for unique objects, then use JSON.stringify in your comparison.

如果要检查惟一对象,则使用JSON。stringify比较。

function arrayUnique(array) {
    var a = array.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(JSON.stringify(a[i]) === JSON.stringify(a[j]))
                a.splice(j--, 1);
        }
    }

    return a;
}

#30


1  

Array.prototype.union = function (other_array) {
/* you can include a test to check whether other_array really is an array */
  other_array.forEach(function(v) { if(this.indexOf(v) === -1) {this.push(v);}}, this);    
}

#1


1162  

To just merge the arrays (without removing duplicates)

只需合并数组(不删除重复项)

ES5 version use Array.concat:

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];

var array3 = array1.concat(array2); // Merges both arrays
// [ 'Vijendra', 'Singh', 'Singh', 'Shakya' ]

ES6 version use destructuring

const array1 = ["Vijendra","Singh"];
const array2 = ["Singh", "Shakya"];
const array3 = [...array1, ...array2];

Since there is no 'built in' way to remove duplicates (ECMA-262 actually has Array.forEach which would be great for this), we have to do it manually:

因为没有“内置”删除重复的方法(ECMA-262实际上有数组)。对于每个人来说,这都是很好的选择,我们必须手动去做:

Array.prototype.unique = function() {
    var a = this.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }

    return a;
};

Then, to use it:

然后,使用它:

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
// Merges both arrays and gets unique items
var array3 = array1.concat(array2).unique(); 

This will also preserve the order of the arrays (i.e, no sorting needed).

这也将保留数组的顺序(i。e,不需要排序)。

Since many people are annoyed about prototype augmentation of Array.prototype and for in loops, here is a less invasive way to use it:

由于许多人对阵列的原型增加感到恼火。原型和在循环中,这是一种侵入性较低的使用方法:

function arrayUnique(array) {
    var a = array.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }

    return a;
}

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
    // Merges both arrays and gets unique items
var array3 = arrayUnique(array1.concat(array2));

For those who are fortunate enough to work with browsers where ES5 is available, you can use Object.defineProperty like this:

对于那些有幸能够在ES5可用的浏览器中工作的人,可以使用Object.defineProperty:

Object.defineProperty(Array.prototype, 'unique', {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function() {
        var a = this.concat();
        for(var i=0; i<a.length; ++i) {
            for(var j=i+1; j<a.length; ++j) {
                if(a[i] === a[j])
                    a.splice(j--, 1);
            }
        }

        return a;
    }
});

#2


492  

With Underscore.js or Lo-Dash you can do:

与强调。js或Lo-Dash:

_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]

http://underscorejs.org/#union

http://underscorejs.org/联盟

http://lodash.com/docs#union

http://lodash.com/docs联盟

#3


175  

First concatenate the two arrays, next filter out only the unique items.

首先连接两个数组,然后只过滤出唯一的项。

var a = [1, 2, 3], b = [101, 2, 1, 10];
var c = a.concat(b);
var d = c.filter(function (item, pos) {return c.indexOf(item) == pos});

// d is [1,2,3,101,10]

http://jsfiddle.net/simo/98622/

http://jsfiddle.net/simo/98622/

Edit

As suggested by @Dmitry (see the second comment below) a more performance wise solution would be to filter out the unique items in b before concatenating with a

正如@Dmitry所建议的(请参阅下面的第二条评论),一个更高效的解决方案是在连接a之前过滤掉b中的唯一项。

var a = [1, 2, 3], b = [101, 2, 1, 10];
var c = a.concat(b.filter(function (item) {
    return a.indexOf(item) < 0;
}));

// d is [1,2,3,101,10]

#4


100  

This is an ECMAScript 6 solution using spread operator and array generics.

这是一个使用扩展操作符和数组泛型的ECMAScript 6解决方案。

Currently it only works with Firefox, and possibly Internet Explorer Technical Preview.

目前它只适用于Firefox,也可能是Internet Explorer技术预览版。

But if you use Babel, you can have it now.

但是如果你使用巴别,你现在就可以拥有它。

// Input: [ [1, 2, 3], [101, 2, 1, 10], [2, 1] ]
// Output: [1, 2, 3, 101, 10]
function mergeDedupe(arr)
{
  return [...new Set([].concat(...arr))];
}

#5


76  

ES6

array1.push(...array2) // => don't remove duplication 

OR

[...array1,...array2] //   =>  don't remove duplication 

OR

[...new Set([...array1 ,...array2])]; //   => remove duplication

#6


31  

Here is a slightly different take on the loop. With some of the optimizations in the latest version of Chrome, it is the fastest method for resolving the union of the two arrays (Chrome 38.0.2111).

这里有一个稍微不同的循环。在最新版本的Chrome中有一些优化,这是解决两个数组的联合的最快方法(Chrome 38.0.2111)。

http://jsperf.com/merge-two-arrays-keeping-only-unique-values

http://jsperf.com/merge-two-arrays-keeping-only-unique-values

var array1 = ["Vijendra", "Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = [];

var arr = array1.concat(array2),
  len = arr.length;

while (len--) {
  var itm = arr[len];
  if (array3.indexOf(itm) === -1) {
    array3.unshift(itm);
  }
}

while loop: ~589k ops/s
filter: ~445k ops/s
lodash: 308k ops/s
for loops: 225k ops/s

while循环:~589k ops/s filter: ~445k ops/s lodash: 308k ops/s for循环:225k ops/s。

A comment pointed out that one of my setup variables was causing my loop to pull ahead of the rest, because it didn't have to initialize an empty array to write to. I agree with that, so I've rewritten the test to even the playing field, and included an even faster option.

有一条评论指出,我的一个设置变量导致我的循环先于其他的,因为它不需要初始化一个空的数组来写。我同意这一点,所以我重写了测试,甚至包括了游戏领域,并且包含了一个更快的选项。

http://jsperf.com/merge-two-arrays-keeping-only-unique-values/21

http://jsperf.com/merge-two-arrays-keeping-only-unique-values/21

var whileLoopAlt = function(array1, array2) {
    var array3 = [];
    var arr = array1.concat(array2);
    var len = arr.length;
    var assoc = {};

    while(len--) {
        var itm = arr[len];

        if(!assoc[itm]) { // Eliminate the indexOf call
            array3.unshift(itm);
            assoc[itm] = true;
        }
    }

    return array3;
};

In this alternate solution, I've combined one answer's associative array solution to eliminate the .indexOf() call in the loop which was slowing things down a lot with a second loop, and included some of the other optimizations that other users have suggested in their answers as well.

在这个替代的解决方案中,我结合了一个答案的关联数组解决方案,以消除循环中的. indexof()调用,该方法通过第二个循环来降低很多东西的速度,并包含了其他用户在回答中所建议的其他一些优化。

The top answer here with the double loop on every value (i-1) is still significantly slower. lodash is still doing strong, and I still would recommend it to anyone who doesn't mind adding a library to their project. For those who don't want to, my while loop is still a good answer and the filter answer has a very strong showing here, beating out all on my tests with the latest Canary Chrome (44.0.2360) as of this writing.

在这里,对于每个值(i-1)的双循环的最上面的答案仍然要慢得多。lodash仍然很强大,我仍然会向任何不介意在项目中添加一个库的人推荐它。对于那些不想这样做的人来说,我的while循环仍然是一个很好的答案,这个过滤器的答案在这里有很强的显示效果,在我的测试中,我用最新的Canary Chrome(44.0.2360)进行了测试。

Check out Mike's answer and Dan Stocker's answer if you want to step it up a notch in speed. Those are by far the fastest of all results after going through almost all of the viable answers.

如果你想加快速度的话,看看麦克的答案和丹·斯托克的回答。到目前为止,这些都是经过几乎所有可行的答案后最快的结果。

#7


25  

You can do it simply with ECMAScript 6,

你可以简单地用ECMAScript 6来做,

var array1 = ["Vijendra", "Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = [...new Set([...array1 ,...array2])];
console.log(array3); // ["Vijendra", "Singh", "Shakya"];
  • Use the spread operator for concatenating the array.
  • 使用扩展操作符来连接数组。
  • Use Set for creating a distinct set of elements.
  • 用于创建一组不同元素的集合。
  • Again use the spread operator to convert the Set into an array.
  • 再次使用扩展操作符将集合转换为数组。

#8


16  

Using a Set (ECMAScript 2015), it will be as simple as that:

使用一个Set (ECMAScript 2015),它将非常简单:

const array1 = ["Vijendra", "Singh"];
const array2 = ["Singh", "Shakya"];
const array3 = Array.from(new Set(array1.concat(array2)));

#9


14  

Array.prototype.merge = function(/* variable number of arrays */){
    for(var i = 0; i < arguments.length; i++){
        var array = arguments[i];
        for(var j = 0; j < array.length; j++){
            if(this.indexOf(array[j]) === -1) {
                this.push(array[j]);
            }
        }
    }
    return this;
};

A much better array merge function.

一个更好的数组合并函数。

#10


13  

Just throwing in my two cents.

只是扔了我两美分。

function mergeStringArrays(a, b){
    var hash = {};
    var ret = [];

    for(var i=0; i < a.length; i++){
        var e = a[i];
        if (!hash[e]){
            hash[e] = true;
            ret.push(e);
        }
    }

    for(var i=0; i < b.length; i++){
        var e = b[i];
        if (!hash[e]){
            hash[e] = true;
            ret.push(e);
        }
    }

    return ret;
}

This is a method I use a lot, it uses an object as a hashlookup table to do the duplicate checking. Assuming that the hash is O(1), then this runs in O(n) where n is a.length + b.length. I honestly have no idea how the browser does the hash, but it performs well on many thousands of data points.

这是一个我经常使用的方法,它使用一个对象作为hashlookup表来执行重复检查。假设哈希是O(1),那么这是在O(n)中,其中n是a。+ b.length长度。老实说,我不知道浏览器是如何处理散列的,但它在成千上万个数据点上执行得很好。

#11


13  

Why don't you use an object? It looks like you're trying to model a set. This won't preserve the order, however.

为什么不用对象呢?看起来你是在尝试建立一个集合,但这不会维持秩序。

var set1 = {"Vijendra":true, "Singh":true}
var set2 = {"Singh":true,  "Shakya":true}

// Merge second object into first
function merge(set1, set2){
  for (var key in set2){
    if (set2.hasOwnProperty(key))
      set1[key] = set2[key]
  }
  return set1
}

merge(set1, set2)

// Create set from array
function setify(array){
  var result = {}
  for (var item in array){
    if (array.hasOwnProperty(item))
      result[array[item]] = true
  }
  return result
}

#12


11  

Just steer clear of nested loops (O(n^2)), and .indexOf() (+O(n)).

只是避开嵌套循环(O(n ^ 2)),和.indexOf()(+ O(n))。

function merge(a, b) {
    var hash = {}, i;
    for (i=0; i<a.length; i++) {
        hash[a[i]]=true;
    } 
    for (i=0; i<b.length; i++) {
        hash[b[i]]=true;
    } 
    return Object.keys(hash);
}

#13


8  

My one and a half penny:

我的一个半便士:

Array.prototype.concat_n_dedupe = function(other_array) {
  return this
    .concat(other_array) // add second
    .reduce(function(uniques, item) { // dedupe all
      if (uniques.indexOf(item) == -1) {
        uniques.push(item);
      }
      return uniques;
    }, []);
};

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];

var result = array1.concat_n_dedupe(array2);

console.log(result);

#14


6  

//Array.indexOf was introduced in javascript 1.6 (ECMA-262) 
//We need to implement it explicitly for other browsers, 
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt, from)
  {
    var len = this.length >>> 0;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}
//now, on to the problem

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];

var merged = array1.concat(array2);
var t;
for(i = 0; i < merged.length; i++)
  if((t = merged.indexOf(i + 1, merged[i])) != -1)
  {
    merged.splice(t, 1);
    i--;//in case of multiple occurrences
  }

Implementation of indexOf method for other browsers is taken from MDC

其他浏览器的indexOf方法的实现是从MDC中获得的。

#15


6  

Simplified simo's answer and turned it into a nice function.

简化了simo的答案,并把它变成了一个很好的函数。

function mergeUnique(arr1, arr2){
    return arr1.concat(arr2.filter(function (item) {
        return arr1.indexOf(item) === -1;
    }));
}

#16


5  

Array.prototype.add = function(b){
    var a = this.concat();                // clone current object
    if(!b.push || !b.length) return a;    // if b is not an array, or empty, then return a unchanged
    if(!a.length) return b.concat();      // if original is empty, return b

    // go through all the elements of b
    for(var i = 0; i < b.length; i++){
        // if b's value is not in a, then add it
        if(a.indexOf(b[i]) == -1) a.push(b[i]);
    }
    return a;
}

// Example:
console.log([1,2,3].add([3, 4, 5])); // will output [1, 2, 3, 4, 5]

#17


5  

The best solution...

最好的解决方案……

You can check directly in the browser console by hitting...

你可以通过点击来直接查看浏览器控制台。

Without duplicate

a = [1, 2, 3];
b = [3, 2, 1, "prince"];

a.concat(b.filter(function(el) {
    return a.indexOf(el) === -1;
}));

With duplicate

["prince", "asish", 5].concat(["ravi", 4])

If you want without duplicate you can try a better solution from here - Shouting Code.

如果你不想复制,你可以从这里尝试一个更好的解决方案——大喊代码。

[1, 2, 3].concat([3, 2, 1, "prince"].filter(function(el) {
    return [1, 2, 3].indexOf(el) === -1;
}));

Try on Chrome browser console

尝试Chrome浏览器控制台。

 f12 > console

Output:

输出:

["prince", "asish", 5, "ravi", 4]

[1, 2, 3, "prince"]

#18


4  

You can achieve it simply using Underscore.js's => uniq:

您可以简单地使用下划线实现它。js = > uniq:

array3 = _.uniq(array1.concat(array2))

console.log(array3)

It will print ["Vijendra", "Singh", "Shakya"].

它将印刷["Vijendra", "Singh", "Shakya"]。

#19


3  

New solution ( which uses Array.prototype.indexOf and Array.prototype.concat ):

新解决方案(使用Array.prototype)。indexOf和Array.prototype。concat):

Array.prototype.uniqueMerge = function( a ) {
    for ( var nonDuplicates = [], i = 0, l = a.length; i<l; ++i ) {
        if ( this.indexOf( a[i] ) === -1 ) {
            nonDuplicates.push( a[i] );
        }
    }
    return this.concat( nonDuplicates )
};

Usage:

用法:

>>> ['Vijendra', 'Singh'].uniqueMerge(['Singh', 'Shakya'])
["Vijendra", "Singh", "Shakya"]

Array.prototype.indexOf ( for internet explorer ):

Array.prototype。indexOf (internet explorer):

Array.prototype.indexOf = Array.prototype.indexOf || function(elt)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0) ? Math.ceil(from): Math.floor(from); 
    if (from < 0)from += len;

    for (; from < len; from++)
    {
      if (from in this && this[from] === elt)return from;
    }
    return -1;
  };

#20


2  

In Dojo 1.6+

在Dojo 1.6 +

var unique = []; 
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = array1.concat(array2); // Merged both arrays

dojo.forEach(array3, function(item) {
    if (dojo.indexOf(unique, item) > -1) return;
    unique.push(item); 
});

Update

更新

See working code.

看到工作代码。

http://jsfiddle.net/UAxJa/1/

http://jsfiddle.net/UAxJa/1/

#21


2  

Merge an unlimited number of arrays or non-arrays and keep it unique:

合并无限数量的数组或非数组,并保持它唯一:

function flatMerge() {
    return Array.prototype.reduce.call(arguments, function (result, current) {
        if (!(current instanceof Array)) {
            if (result.indexOf(current) === -1) {
                result.push(current);
            }
        } else {
            current.forEach(function (value) {
                console.log(value);
                if (result.indexOf(value) === -1) {
                    result.push(value);
                }
            });
        }
        return result;
    }, []);
}

flatMerge([1,2,3], 4, 4, [3, 2, 1, 5], [7, 6, 8, 9], 5, [4], 2, [3, 2, 5]);
// [1, 2, 3, 4, 5, 7, 6, 8, 9]

flatMerge([1,2,3], [3, 2, 1, 5], [7, 6, 8, 9]);
// [1, 2, 3, 5, 7, 6, 8, 9]

flatMerge(1, 3, 5, 7);
// [1, 3, 5, 7]

#22


2  

Assuming original arrays don't need de-duplication, this should be pretty fast, retain original order, and does not modify the original arrays...

假设原始数组不需要去复制,这应该是非常快的,保留原始的顺序,并且不修改原始数组…

function arrayMerge(base, addendum){
    var out = [].concat(base);
    for(var i=0,len=addendum.length;i<len;i++){
        if(base.indexOf(addendum[i])<0){
            out.push(addendum[i]);
        }
    }
    return out;
}

usage:

用法:

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = arrayMerge(array1, array2);

console.log(array3);
//-> [ 'Vijendra', 'Singh', 'Shakya' ]

#23


2  

A functional approach with ES2015

Following the functional approach a union of two Arrays is just the composition of concat and filter. In order to provide optimal performance we resort to the native Set data type, which is optimized for property lookups.

在函数方法之后,两个数组的结合就是concat和filter的组合。为了提供最优的性能,我们采用了本机集数据类型,这是针对属性查找优化的。

Anyway, the key question in conjunction with a union function is how to treat duplicates. The following permutations are possible:

总之,结合一个联合函数的关键问题是如何处理重复。以下排列是可能的:

Array A      + Array B

[unique]     + [unique]
[duplicated] + [unique]
[unique]     + [duplicated]
[duplicated] + [duplicated]

The first two permutations are easy to handle with a single function. However, the last two are more complicated, since you can't process them as long as you rely on Set lookups. Since switching to plain old Object property lookups would entail a serious performance hit the following implementation just ignores the third and fourth permutation. You would have to build a separate version of union to support them.

前两个排列很容易处理单个函数。但是,最后两个比较复杂,因为只要依赖设置查找,就无法处理它们。由于切换到普通的旧对象属性查找会导致严重的性能损失,所以下面的实现只会忽略第三和第四个排列。你必须建立一个独立的联盟来支持他们。


// small, reusable auxiliary functions

const comp = f => g => x => f(g(x));
const apply = f => a => f(a);
const flip = f => b => a => f(a) (b);
const concat = xs => y => xs.concat(y);
const afrom = apply(Array.from);
const createSet = xs => new Set(xs);
const filter = f => xs => xs.filter(apply(f));


// de-duplication

const dedupe = comp(afrom) (createSet);


// the actual union function

const union = xs => ys => {
  const zs = createSet(xs);  
  return concat(xs) (
    filter(x => zs.has(x)
     ? false
     : zs.add(x)
  ) (ys));
}


// mock data

const xs = [1,2,2,3,4,5];
const ys = [0,1,2,3,3,4,5,6,6];


// here we go

console.log( "unique/unique", union(dedupe(xs)) (ys) );
console.log( "duplicated/unique", union(xs) (ys) );

From here on it gets trivial to implement an unionn function, which accepts any number of arrays (inspired by naomik's comments):

从这里开始,实现一个unionn函数变得很简单,该函数接受任意数量的数组(受naomik的注释启发):

// small, reusable auxiliary functions

const uncurry = f => (a, b) => f(a) (b);
const foldl = f => acc => xs => xs.reduce(uncurry(f), acc);

const apply = f => a => f(a);
const flip = f => b => a => f(a) (b);
const concat = xs => y => xs.concat(y);
const createSet = xs => new Set(xs);
const filter = f => xs => xs.filter(apply(f));


// union and unionn

const union = xs => ys => {
  const zs = createSet(xs);  
  return concat(xs) (
    filter(x => zs.has(x)
     ? false
     : zs.add(x)
  ) (ys));
}

const unionn = (head, ...tail) => foldl(union) (head) (tail);


// mock data

const xs = [1,2,2,3,4,5];
const ys = [0,1,2,3,3,4,5,6,6];
const zs = [0,1,2,3,4,5,6,7,8,9];


// here we go

console.log( unionn(xs, ys, zs) );

It turns out unionn is just foldl (aka Array.prototype.reduce), which takes union as its reducer. Note: Since the implementation doesn't use an additional accumulator, it will throw an error when you apply it without arguments.

结果表明,unionn只是foldl(即Array.prototype.reduce),它将union作为它的减速器。注意:由于实现不使用额外的累加器,所以当您不使用参数的时候,它会抛出一个错误。

#24


2  

The easiest way to do this is either to use concat() to merge the arrays and then use filter() to remove the duplicates, or to use concat() and then put the merged array inside a Set().

最简单的方法是使用concat()合并数组,然后使用filter()来删除重复项,或者使用concat(),然后将合并的数组放入Set()中。

First way:

第一个方法:

const firstArray = [1,2, 2];
const secondArray = [3,4];
// now lets merge them
const mergedArray = firstArray.concat(secondArray); // [1,2,2,3,4]
//now use filter to remove dups
const removeDuplicates = mergedArray.filter((elem, index) =>  mergedArray.indexOf(elem) === index); // [1,2,3, 4]

Second way (but with performance implications on the UI):

第二种方法(但对UI的性能影响):

const firstArray = [1,2, 2];
const secondArray = [3,4];
// now lets merge them
const mergedArray = firstArray.concat(secondArray); // [1,2,2,3,4]
const removeDuplicates = new Set(mergedArray);

#25


2  

The best and simplest way to do that is using the function "some()" of JavaScript that returns true or false indicating if the array contains the object's element. You can make this:

最好最简单的方法是使用函数“some()”来返回true或false,表示数组是否包含对象元素。你可以这样:

var array1 = ["Vijendra","Singh"]; 
var array2 = ["Singh", "Shakya"];

var array3 = array1;

array2.forEach(function(elementArray2){
    var isEquals = array1.some(function(elementArray1){
        return elementArray1 === elementArray2;
    })
    if(!isEquals){
        array3.push(elementArray2);
    }
});
console.log(array3);

The results:

结果:

["Vijendra", "Singh", "Shakya"]

ss you wish... without duplicate it...

党*你希望……没有重复的…

#26


2  

looks like the accepted answer is the slowest in my tests;

看起来接受的答案是我测试中最慢的。

note I am merging 2 arrays of objects by Key

注意,我正在合并两个对象数组。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<button type='button' onclick='doit()'>do it</button>
<script>
function doit(){
    var items = [];
    var items2 = [];
    var itemskeys = {};
    for(var i = 0; i < 10000; i++){
        items.push({K:i, C:"123"});
        itemskeys[i] = i;
    }

    for(var i = 9000; i < 11000; i++){
        items2.push({K:i, C:"123"});
    }

    console.time('merge');
    var res = items.slice(0);

    //method1();
    method0();
    //method2();

    console.log(res.length);
    console.timeEnd('merge');

    function method0(){
        for(var i = 0; i < items2.length; i++){
            var isok = 1;
            var k = items2[i].K;
            if(itemskeys[k] == null){
                itemskeys[i] = res.length;
                res.push(items2[i]);
            }
        }
    }

    function method1(){
        for(var i = 0; i < items2.length; i++){
            var isok = 1;
            var k = items2[i].K;

            for(var j = 0; j < items.length; j++){
                if(items[j].K == k){
                    isok = 0;
                    break;
                }
            }

            if(isok) res.push(items2[i]);
        }  
    }

    function method2(){
        res = res.concat(items2);
        for(var i = 0; i < res.length; ++i) {
            for(var j = i+1; j < res.length; ++j) {
                if(res[i].K === res[j].K)
                    res.splice(j--, 1);
            }
        }
    }
}
</script>
</body>
</html>

#27


1  

var MergeArrays=function(arrayOne, arrayTwo, equalityField) {
    var mergeDictionary = {};

    for (var i = 0; i < arrayOne.length; i++) {
        mergeDictionary[arrayOne[i][equalityField]] = arrayOne[i];
    }

    for (var i = 0; i < arrayTwo.length; i++) {
        mergeDictionary[arrayTwo[i][equalityField]] = arrayTwo[i];
    }

    return $.map(mergeDictionary, function (value, key) { return value });
}

Leveraging dictionaries and Jquery you could merge the two arrays and not get duplicates. In my example I'm using a given field on the object but could be just the object itself.

利用词典和Jquery可以合并这两个数组,而不是复制。在我的例子中,我在对象上使用给定的字段,但可能只是对象本身。

#28


1  

Another approach for your review with reduce func:

另一种减少func的方法是:

function mergeDistinct(arResult, candidate){
  if (-1 == arResult.indexOf(candidate)) {
    arResult.push(candidate);
  }
  return arResult;
}

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];

var arMerge = [];
arMerge = array1.reduce(mergeDistinct, arMerge);
arMerge = array2.reduce(mergeDistinct, arMerge);//["Vijendra","Singh","Shakya"];

#29


1  

If you want to check for unique objects, then use JSON.stringify in your comparison.

如果要检查惟一对象,则使用JSON。stringify比较。

function arrayUnique(array) {
    var a = array.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(JSON.stringify(a[i]) === JSON.stringify(a[j]))
                a.splice(j--, 1);
        }
    }

    return a;
}

#30


1  

Array.prototype.union = function (other_array) {
/* you can include a test to check whether other_array really is an array */
  other_array.forEach(function(v) { if(this.indexOf(v) === -1) {this.push(v);}}, this);    
}