我有两个JavaScript数组:

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

我希望输出为:

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

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

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


当前回答

使用Lodash

我发现@GijsjanB的答案很有用,但我的数组包含具有许多属性的对象,因此我不得不使用其中一个属性来消除它们的重复。

这是我使用lodash的解决方案

userList1 = [{ id: 1 }, { id: 2 }, { id: 3 }]
userList2 = [{ id: 3 }, { id: 4 }, { id: 5 }]
// id 3 is repeated in both arrays

users = _.unionWith(userList1, userList2, function(a, b){ return a.id == b.id });

// users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }]

作为第三个参数传递的函数有两个参数(两个元素),如果它们相等,则必须返回true。

其他回答

ES6提供了一种单线解决方案,通过使用析构函数和集合来合并多个数组而不重复。

const array1 = ['a','b','c'];
const array2 = ['c','c','d','e'];
const array3 = [...new Set([...array1,...array2])];
console.log(array3); // ["a", "b", "c", "d", "e"]
var a = [1,2,3]
var b = [1,2,4,5]

我喜欢一行。这将把不同的b元素推到

b.forEach(item => a.includes(item) ? null : a.push(item));

另一个版本不会修改

var c = a.slice();
b.forEach(item => c.includes(item) ? null : c.push(item));

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

   //1.merge two array into one array

   var arr1 = [0, 1, 2, 4];
   var arr2 = [4, 5, 6];

   //for merge array we use "Array.concat"

   let combineArray = arr1.concat(arr2); //output

   alert(combineArray); //now out put is 0,1,2,4,4,5,6 but 4 reapeat

   //2.same thing with "Spread Syntex"

   let spreadArray = [...arr1, ...arr2];

   alert(spreadArray);  //now out put is 0,1,2,4,4,5,6 but 4 reapete


   /*
       if we need remove duplicate element method use are
       1.Using set
       2.using .filter
       3.using .reduce
   */
const array3 = array1.filter(t=> !array2.includes(t)).concat(array2)