我有两个JavaScript数组:

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

我希望输出为:

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

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

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


当前回答

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

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

其他回答

您可以使用loadash unionWith-_.unionWith(〔arrays〕,〔comparator〕)

此方法类似于_.union,只是它接受被调用来比较数组元素的比较器。结果值从出现该值的第一个数组中选择。比较器由两个参数调用:(arrVal,othVal)。

var array1=[“Vijendra”,“Singh”];var array2=[“Singh”,“Shakya”];var array3=_.unionWith(array1,array2,_.isEqual);console.log(array3);<script src=“https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js“></script>

使用Undercore.js或Lo Dash,您可以执行以下操作:

console.log(_.union([1,2,3],[101,2,1,10],[2,1]));<script src=“https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js“></script>

http://underscorejs.org/#union

http://lodash.com/docs#union

Array.prototype.add = function(b){
    var a = this.concat();                // clone current object
    if(!b.push || !b.length) return a;    // if b is not an array, or empty, then return a unchanged
    if(!a.length) return b.concat();      // if original is empty, return b

    // go through all the elements of b
    for(var i = 0; i < b.length; i++){
        // if b's value is not in a, then add it
        if(a.indexOf(b[i]) == -1) a.push(b[i]);
    }
    return a;
}

// Example:
console.log([1,2,3].add([3, 4, 5])); // will output [1, 2, 3, 4, 5]

只需使用Undercore.js的=>uniq即可实现:

array3 = _.uniq(array1.concat(array2))

console.log(array3)

它将印刷[“Vijendra”、“Singh”、“Shakya”]。

Array.prototype.pushUnique = function(values)
{
    for (var i=0; i < values.length; i++)
        if (this.indexOf(values[i]) == -1)
            this.push(values[i]);
};

Try:

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
array1.pushUnique(array2);
alert(array1.toString());  // Output: Vijendra,Singh,Shakya