我有两个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 union = function (a, b) {
for (var i = 0; i < b.length; i++)
if (a.indexOf(b[i]) === -1)
a.push(b[i]);
return a;
};
var a = [1, 2, 3, 'a', 'b', 'c'];
var b = [2, 3, 4, 'b', 'c', 'd'];
a = union(a, b);
//> [1, 2, 3, "a", "b", "c", 4, "d"]
var array1 = ["Vijendra", "Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = union(array1, array2);
//> ["Vijendra", "Singh", "Shakya"]
其他回答
我简化了这个答案的最佳部分,并将其转化为一个很好的函数:
function mergeUnique(arr1, arr2){
return arr1.concat(arr2.filter(function (item) {
return arr1.indexOf(item) === -1;
}));
}
作为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);
ES 6版本
试试这个。。。这应该能解决你的问题
var array1=[“Vijendra”,“Singh”];var array2=[“Singh”,“Shakya”];
var输出=[…new Set([…array1,…array2])]
console.log(“合并数组”,输出)
使用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
最好也是最简单的方法是使用JavaScript的函数“some()”,该函数返回true或false,指示数组是否包含对象的元素。您可以这样做:
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = array1;
array2.forEach(function(elementArray2){
var isEquals = array1.some(function(elementArray1){
return elementArray1 === elementArray2;
})
if(!isEquals){
array3.push(elementArray2);
}
});
console.log(array3);
结果:
["Vijendra", "Singh", "Shakya"]
如你所愿。。。无需复制。。。