我有两个数组
var array1 = [{firstName:'John', age:32, email:'[email protected]'}, {firstName:'Jack', age:40, email:'[email protected]'}];
var array2 = [{firstName:'Jen', age:29, email:'[email protected]'}, {firstName:'Jack', age:40, email:'[email protected]'}];
我想合并两个数组并获得以下输出
var array3 = [{firstName:'John', age:32, email:'[email protected]'}, {firstName:'Jack', age:40, email:'[email protected]'}, {firstName: 'Jen', age: 29, email: '[email protected]'}];
想知道在JavaScript中合并两个数组的最佳方法,以便从每个数组中仅获得唯一的项吗?
使用Rest参数,Set对象和JSON方法:
[ ...new Set([...a1, ...a2].map(JSON.stringify)) ].map(JSON.parse);
var array1 = [{firstName:'John', age:32, email:'[email protected]'}, {firstName:'Jack', age:40, email:'[email protected]'}];
var array2 = [{firstName:'Jen', age:29, email:'[email protected]'}, {firstName:'Jack', age:40, email:'[email protected]'}];
function joinArrays(a1, a2) {
return [ ...new Set([...a1, ...a2].map(JSON.stringify)) ].map(JSON.parse);
}
console.log(joinArrays(array1, array2));
如果您尝试使用google来获得答案是相当容易的,但是使用es6语法可以通过以下方式完成:
[...new Set([...array1, ...array2])]