我有两个JavaScript数组:
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
我希望输出为:
var array3 = ["Vijendra","Singh","Shakya"];
输出数组应删除重复的单词。
如何在JavaScript中合并两个数组,以便从每个数组中只获得唯一的项目,其顺序与它们插入原始数组的顺序相同?
我有两个JavaScript数组:
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
我希望输出为:
var array3 = ["Vijendra","Singh","Shakya"];
输出数组应删除重复的单词。
如何在JavaScript中合并两个数组,以便从每个数组中只获得唯一的项目,其顺序与它们插入原始数组的顺序相同?
当前回答
var array1=[“一”,“二”];var array2=[“two”,“three”];var collectionOfTwoArrays=[…array1,…array2];var uniqueList=array=>[…new Set(array)];console.log('集合:');console.log(collectionOfTwoArrays);console.log('没有重复项的集合:');console.log(uniqueList(collectionOfTwoArrays));
其他回答
对于大型输入,更好的选择是对数组进行排序。然后合并它们。
function sortFunction(a, b) {
return a - b;
}
arr1.sort(sortFunction);
arr2.sort(sortFunction);
function mergeDedup(arr1, arr2) {
var i = 0, j = 0, result = [];
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
writeIfNotSameAsBefore(result, arr1[i]);
i++;
}
else if (arr1[i] > arr2[j]) {
writeIfNotSameAsBefore(result, arr2[j]);
j++;
}
else {
writeIfNotSameAsBefore(result, arr1[i]);
i++;
j++;
}
}
while (i < arr1.length) {
writeIfNotSameAsBefore(result, arr1[i]);
i++;
}
while (j < arr2.length) {
writeIfNotSameAsBefore(result, arr2[j]);
j++;
}
return result;
}
function writeIfNotSameAsBefore(arr, item) {
if (arr[arr.length - 1] !== item) {
arr[arr.length] = item;
}
return arr.length;
}
排序将采用O(nlogn+mlogm),其中n和m是数组的长度,O(x)用于合并,其中x=Max(n,m);
使用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。
之前写过同样的原因(适用于任意数量的数组):
/**
* Returns with the union of the given arrays.
*
* @param Any amount of arrays to be united.
* @returns {array} The union array.
*/
function uniteArrays()
{
var union = [];
for (var argumentIndex = 0; argumentIndex < arguments.length; argumentIndex++)
{
eachArgument = arguments[argumentIndex];
if (typeof eachArgument !== 'array')
{
eachArray = eachArgument;
for (var index = 0; index < eachArray.length; index++)
{
eachValue = eachArray[index];
if (arrayHasValue(union, eachValue) == false)
union.push(eachValue);
}
}
}
return union;
}
function arrayHasValue(array, value)
{ return array.indexOf(value) != -1; }
这很简单,可以用jQuery在一行中完成:
var arr1 = ['Vijendra', 'Singh'], arr2 =['Singh', 'Shakya'];
$.unique(arr1.concat(arr2))//one line
["Vijendra", "Singh", "Shakya"]
我认为这工作得更快。
removeDup = a => {
for (let i = a.length - 1; i >= 0; i--) {
for (let j = i-1; j >= 0; j--) {
if (a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
}