我有两个JavaScript数组:

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

我希望输出为:

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

输出数组应删除重复的单词。

如何在JavaScript中合并两个数组,以便从每个数组中只获得唯一的项目,其顺序与它们插入原始数组的顺序相同?


当前回答

//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
  }

其他浏览器的indexOf方法的实现取自MDC

其他回答

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

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 )
};

用法:

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

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;
  };

合并两个阵列有很多解决方案。它们可以分为两大类(除了使用lodash或underline.js等第三方库)。

a) 组合两个数组并删除重复项。

b) 在组合项目之前过滤掉它们。

合并两个数组并删除重复项

结合

// mutable operation(array1 is the combined array)
array1.push(...array2);
array1.unshift(...array2);

// immutable operation
const combined = array1.concat(array2);
const combined = [...array1, ...array2];    // ES6

统一

统一数组有很多方法,我个人建议使用以下两种方法。

// a little bit tricky
const merged = combined.filter((item, index) => combined.indexOf(item) === index);
const merged = [...new Set(combined)];

在组合项目之前筛选出项目

还有很多方法,但我个人建议使用以下代码,因为它简单。

const merged = array1.concat(array2.filter(secItem => !array1.includes(secItem)));

下面是使用Set的另一个简单解决方案:

常量o1={a:1};const arr1=['!@#$%^&*()','gh',123,o1,1,true,undefined,null];常量arr2=['!@#$%^&*()',123,'abc',o1,0x001,true,void 0,0];const mergeUnique=(…args)=>[…新集合([].contat(…arg))];console.log(mergeUnique(arr1,arr2));

我简化了这个答案的最佳部分,并将其转化为一个很好的函数:

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

我学会了一种用扩展运算符连接两个数组的小方法:

var array1 = ['tom', 'dick', 'harry'];
var array2 = ['martin', 'ricky'];

array1.push(...array2);

“…”扩展运算符将以下数组拆分为单个项,然后push可以将它们作为单独的参数处理。