我有两个JavaScript数组:

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

我希望输出为:

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

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

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


当前回答

最佳解决方案。。。

您可以直接在浏览器控制台中点击。。。

无重复项

a = [1, 2, 3];
b = [3, 2, 1, "prince"];

a.concat(b.filter(function(el) {
    return a.indexOf(el) === -1;
}));

具有重复项

["prince", "asish", 5].concat(["ravi", 4])

如果你想要没有重复,你可以从这里尝试一个更好的解决方案-大喊代码。

[1, 2, 3].concat([3, 2, 1, "prince"].filter(function(el) {
    return [1, 2, 3].indexOf(el) === -1;
}));

在Chrome浏览器控制台上试用

 f12 > console

输出:

["prince", "asish", 5, "ravi", 4]

[1, 2, 3, "prince"]

其他回答

这是我的解决方案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"]
]

对于ES6,只有一行:

a = [1, 2, 3, 4]
b = [4, 5]
[...new Set(a.concat(b))]  // [1, 2, 3, 4, 5]

合并两个阵列有很多解决方案。它们可以分为两大类(除了使用lodash或underline.js等第三方库)。

a) 组合两个数组并删除重复项。

b) 在组合项目之前过滤掉它们。

合并两个数组并删除重复项

结合

// mutable operation(array1 is the combined array)
array1.push(...array2);
array1.unshift(...array2);

// immutable operation
const combined = array1.concat(array2);
const combined = [...array1, ...array2];    // ES6

统一

统一数组有很多方法,我个人建议使用以下两种方法。

// a little bit tricky
const merged = combined.filter((item, index) => combined.indexOf(item) === index);
const merged = [...new Set(combined)];

在组合项目之前筛选出项目

还有很多方法,但我个人建议使用以下代码,因为它简单。

const merged = array1.concat(array2.filter(secItem => !array1.includes(secItem)));

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

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

在当今时代,使用现有的图书馆提供更简单、更优雅的内容:

import {pipe, concat, distinct} from 'iter-ops';

// our inputs:
const array1 = ['Vijendra', 'Singh'];
const array2 = ['Singh', 'Shakya'];

const i = pipe(
    array1,
    concat(array2), // adding array
    distinct() // making it unique
);

console.log([...i]); //=> ['Vijendra', 'Singh', 'Shakya']

这两者都是高性能的,因为我们只迭代一次,而且代码非常容易阅读。

注:我是iter ops的作者。