我有两个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 array3 = array1.filter(t=> !array2.includes(t)).concat(array2)

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

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

array1.push(...array2);

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

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

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

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

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

可以使用Set完成。

var array1=[“Vijendra”,“Singh”];var array2=[“Singh”,“Shakya”];var array3=array1.concat(array2);var tempSet=新集合(array3);array3=Array.from(tempSet);//显示输出document.body.querySelector(“div”).innerHTML=JSON.stringify(array3);<div style=“width:100%;height:4rem;line height:4rem;background color:steelblue;color:#DDD;text align:center;font-family:Calibri”>临时文本</div>