我有两个JavaScript数组:

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

我希望输出为:

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

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

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


当前回答

const array3 = array1.filter(t=> !array2.includes(t)).concat(array2)

其他回答

const array3 = array1.filter(t=> !array2.includes(t)).concat(array2)
//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.pushUnique = function(values)
{
    for (var i=0; i < values.length; i++)
        if (this.indexOf(values[i]) == -1)
            this.push(values[i]);
};

Try:

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
array1.pushUnique(array2);
alert(array1.toString());  // Output: Vijendra,Singh,Shakya

Use:

Array.prototype.merge = function (arr) {
    var key;
    for(key in arr) 
        this[key] = arr[key];
};

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

函数合并(a,b){var哈希={};变量i;对于(i=0;i<a.length;i++){hash[a[i]=真;}对于(i=0;i<b.length;i++){hash[b[i]]=真;}return Object.keys(哈希);}var array1=[“Vijendra”,“Singh”];var array2=[“Singh”,“Shakya”];var array3=合并(array1,array2);console.log(array3);