我有两个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

取两个数组a和b

var a = ['a','b','c'];

var b = ['d','e','f'];
var c = a.concat(b); 


//c is now an an array with: ['a','b','c','d','e','f']

Use:

Array.prototype.merge = function (arr) {
    var key;
    for(key in arr) 
        this[key] = arr[key];
};

合并两个阵列有很多解决方案。它们可以分为两大类(除了使用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)));

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