我有两个JavaScript数组:

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

我希望输出为:

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

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

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


当前回答

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

其他回答

array1.concat(array2).filter((value, pos, arr)=>arr.indexOf(value)===pos)

这一行的优点在于性能,而且在使用数组时,通常都是链接方法,如filter、map等,因此您可以添加这一行,它将使用array1对array2进行合并和重复数据消除,而无需引用后面的一行(当您链接没有的方法时),例如:

someSource()
.reduce(...)
.filter(...)
.map(...) 
// and now you want to concat array2 and deduplicate:
.concat(array2).filter((value, pos, arr)=>arr.indexOf(value)===pos)
// and keep chaining stuff
.map(...)
.find(...)
// etc

(我不想污染Array.prototype,这将是尊重链的唯一方式——定义一个新函数将打破它——所以我认为这样做是实现这一点的唯一方式)

如果要检查唯一对象,请在比较中使用JSON.stringify。

function arrayUnique(array) {
    var a = array.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(JSON.stringify(a[i]) === JSON.stringify(a[j]))
                a.splice(j--, 1);
        }
    }

    return a;
}

只需避开嵌套循环(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);

对于n个数组,可以这样得到并集。

function union(arrays) {
    return new Set(arrays.flat()).keys();
};

合并无限数量的数组或非数组并保持其唯一性:

function flatMerge() {
    return Array.prototype.reduce.call(arguments, function (result, current) {
        if (!(current instanceof Array)) {
            if (result.indexOf(current) === -1) {
                result.push(current);
            }
        } else {
            current.forEach(function (value) {
                console.log(value);
                if (result.indexOf(value) === -1) {
                    result.push(value);
                }
            });
        }
        return result;
    }, []);
}

flatMerge([1,2,3], 4, 4, [3, 2, 1, 5], [7, 6, 8, 9], 5, [4], 2, [3, 2, 5]);
// [1, 2, 3, 4, 5, 7, 6, 8, 9]

flatMerge([1,2,3], [3, 2, 1, 5], [7, 6, 8, 9]);
// [1, 2, 3, 5, 7, 6, 8, 9]

flatMerge(1, 3, 5, 7);
// [1, 3, 5, 7]