我有两个JavaScript数组:

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

我希望输出为:

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

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

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


当前回答

如果像我一样,您需要支持较旧的浏览器,这适用于IE6+

function es3Merge(a, b) {
    var hash = {},
        i = (a = a.slice(0)).length,
        e;

    while (i--) {
        hash[a[i]] = 1;
    }

    for (i = 0; i < b.length; i++) {
        hash[e = b[i]] || a.push(e);
    }

    return a;
};

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

其他回答

如果您有非常大的列表,则不执行此操作,因为已经记录了许多解决方案,所以这不适合合并,但我用此解决方案解决了我的问题(因为大多数数组过滤解决方案都适用于简单数组)

const uniqueVehiclesServiced = 
  invoice.services.sort().filter(function(item, pos, ary) {
    const firstIndex = invoice.services.findIndex((el, i, arr) => el.product.vin === item.product.vin)

  return !pos || firstIndex == pos;
});

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

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

使用Lodash

我发现@GijsjanB的答案很有用,但我的数组包含具有许多属性的对象,因此我不得不使用其中一个属性来消除它们的重复。

这是我使用lodash的解决方案

userList1 = [{ id: 1 }, { id: 2 }, { id: 3 }]
userList2 = [{ id: 3 }, { id: 4 }, { id: 5 }]
// id 3 is repeated in both arrays

users = _.unionWith(userList1, userList2, function(a, b){ return a.id == b.id });

// users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }]

作为第三个参数传递的函数有两个参数(两个元素),如果它们相等,则必须返回true。

如果您纯粹使用underscore.js,它没有unionWith、unionBy

您可以尝试:_uniq(_.union(arr1,arr2),(obj)=>obj.key)(key是每个对象的关键参数)这将有助于在两个数组合并后获得唯一性。

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