我有两个JavaScript数组:

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

我希望输出为:

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

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

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


当前回答

var arr1 = [1, 3, 5, 6];
var arr2 = [3, 6, 10, 11, 12];
arr1.concat(arr2.filter(ele => !arr1.includes(ele)));
console.log(arr1);

output :- [1, 3, 5, 6, 10, 11, 12]

其他回答

如果像我一样,您需要支持较旧的浏览器,这适用于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

如果您合并对象数组,请考虑使用lodash UnionBy函数,它允许您设置自定义谓词比较对象:

import { unionBy } from 'lodash';

const a = [{a: 1, b: 2}];
const b = [{a: 1, b: 3}];
const c = [{a: 2, b: 4}];

const result = UnionBy(a,b,c, x => x.a);

结果是:〔{a:1;b:2},{a:2;b:4}〕

结果中使用了来自数组的第一个传递匹配

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

使现代化

参见工作代码。

http://jsfiddle.net/UAxJa/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);    
}

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

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

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

常量输入=[[1, 2, 3],[101, 2, 1, 10],[2, 1]];常量合并重复数据消除=(arr)=>{return[…new Set([].contat(…arr))];}console.log(“输出”,合并重复数据消除(输入));