我有两个JavaScript数组:

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

我希望输出为:

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

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

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


当前回答

这是我的解决方案https://gist.github.com/4692150深度相等且易于使用的结果:

function merge_arrays(arr1,arr2)
{
   ... 
   return {first:firstPart,common:commonString,second:secondPart,full:finalString}; 
}

console.log(merge_arrays(
[
[1,"10:55"] ,
[2,"10:55"] ,
[3,"10:55"]
],[
[3,"10:55"] ,
[4,"10:55"] ,
[5,"10:55"]
]).second);

result:
[
[4,"10:55"] ,
[5,"10:55"]
]

其他回答

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

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

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

/***对仅保留唯一值的数组进行重复数据消除。*使用哈希表(js对象)过滤重复项。*保持数组元素的顺序。*该算法对于大型阵列(线性时间)特别有效。*/函数数组UniqueFast(arr){var seen={};var结果=[];变量i,长度=arr.length;对于(i=0;i<len;i++){var项目=arr[i];//哈希表查找if(!seed[item]){result.push(项);seed[项目]=真;}}返回结果;}/////测试var array1=[“Vijendra”,“Singh”];var array2=[“Singh”,“Shakya”];var result=arrayUniqueFast(array1.concat(array2));document.write('<br>result:'+result);

有关阵列重复数据消除的其他方法,请参阅我的基准测试:https://jsperf.com/de-duplicate-an-array-keeping-only-unique-values

给定两个没有重复的简单类型的排序数组,这将在O(n)时间内合并它们,并且输出也将被排序。

function merge(a, b) {
    let i=0;
    let j=0;
    let c = [];
    for (;;) {
        if (i == a.length) {
            if (j == b.length) return c;
            c.push(b[j++]);
        } else if (j == b.length || a[i] < b[j]) {
            c.push(a[i++]);
        } else {
            if (a[i] == b[j]) ++i;   // skip duplicates
            c.push(b[j++]);
        }
    }
}

作为LiraNuna的一部分的单线解决方案:

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

// Merges both arrays
let array3 = array1.concat(array2); 

//REMOVE DUPLICATE
let removeDuplicate = [...new Set(array3)];
console.log(removeDuplicate);