我有两个JavaScript数组:

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

我希望输出为:

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

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

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


当前回答

我的一便士半:

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

其他回答

//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.contat()和array.filter()使用新的Set对象和Spread操作符使用array.contat和新的Set对象

设数组1=[1,2,3,4,5]设数组2=[1,4,6,9]//使用array.contat和array.filter常量array3=array1.concat(array2.filter((项)=>array1.indexOf(项)==-1))console.log('array3:',array3);//使用新的集合和排列运算符const array4=[…新集合([…array1,…array2])];console.log('array4:',array4);//使用array.contat和新集合const array5=[…新集合(array1.concat(array2))];console.log('array5:',array5);

使用集合(ECMAScript 2015),将非常简单:

const array1=[“Vijendra”,“Singh”];const array2=[“Singh”,“Shakya”];console.log(Array.from(new Set(array1.concat(array2))));

这是我的第二个答案,但我相信最快的答案是什么?我希望有人帮我检查并在评论中回复。

我的第一次尝试达到了99k操作/秒,这一次的复测是390k操作/每秒,而另一次领先的jsperf测试是140k(对我来说)。

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

这次我尝试尽可能减少阵列交互,看起来我获得了一些性能。

function findMerge(a1, a2) {
    var len1 = a1.length;

    for (var x = 0; x < a2.length; x++) {
        var found = false;

        for (var y = 0; y < len1; y++) {
            if (a2[x] === a1[y]) {
                found = true;
                break;
            }
        }

        if(!found){
            a1.push(a2.splice(x--, 1)[0]);
        }
    }

    return a1;
}

编辑:我对我的功能做了一些更改,与jsperf站点上的其他功能相比,性能非常出色。

您可以合并结果并过滤重复项:

let combinedItems = [];

// items is an Array of arrays: [[1,2,3],[1,5,6],...]    
items.forEach(currItems => {
    if (currItems && currItems.length > 0) {
        combinedItems = combinedItems.concat(currItems);
    }
});

let noDuplicateItems = combinedItems.filter((item, index) => {
    return !combinedItems.includes(item, index + 1);
});