我有两个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中合并两个数组,以便从每个数组中只获得唯一的项目,其顺序与它们插入原始数组的顺序相同?
当前回答
作为LiraNuna的一部分的单线解决方案:
let array1 = ["Vijendra","Singh"];
let array2 = ["Singh", "Shakya"];
// Merges both arrays
let array3 = array1.concat(array2);
//REMOVE DUPLICATE
let removeDuplicate = [...new Set(array3)];
console.log(removeDuplicate);
其他回答
我的一便士半:
Array.prototype.concat_n_dedupe = function(other_array) {
return this
.concat(other_array) // add second
.reduce(function(uniques, item) { // dedupe all
if (uniques.indexOf(item) == -1) {
uniques.push(item);
}
return uniques;
}, []);
};
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var result = array1.concat_n_dedupe(array2);
console.log(result);
使用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。
如果您有非常大的列表,则不执行此操作,因为已经记录了许多解决方案,所以这不适合合并,但我用此解决方案解决了我的问题(因为大多数数组过滤解决方案都适用于简单数组)
const uniqueVehiclesServiced =
invoice.services.sort().filter(function(item, pos, ary) {
const firstIndex = invoice.services.findIndex((el, i, arr) => el.product.vin === item.product.vin)
return !pos || firstIndex == pos;
});
ES 6版本
试试这个。。。这应该能解决你的问题
var array1=[“Vijendra”,“Singh”];var array2=[“Singh”,“Shakya”];
var输出=[…new Set([…array1,…array2])]
console.log(“合并数组”,输出)
array1.concat(array2).filter((value, pos, arr)=>arr.indexOf(value)===pos)
这一行的优点在于性能,而且在使用数组时,通常都是链接方法,如filter、map等,因此您可以添加这一行,它将使用array1对array2进行合并和重复数据消除,而无需引用后面的一行(当您链接没有的方法时),例如:
someSource()
.reduce(...)
.filter(...)
.map(...)
// and now you want to concat array2 and deduplicate:
.concat(array2).filter((value, pos, arr)=>arr.indexOf(value)===pos)
// and keep chaining stuff
.map(...)
.find(...)
// etc
(我不想污染Array.prototype,这将是尊重链的唯一方式——定义一个新函数将打破它——所以我认为这样做是实现这一点的唯一方式)