我有两个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中合并两个数组,以便从每个数组中只获得唯一的项目,其顺序与它们插入原始数组的顺序相同?
当前回答
ES 6版本
试试这个。。。这应该能解决你的问题
var array1=[“Vijendra”,“Singh”];var array2=[“Singh”,“Shakya”];
var输出=[…new Set([…array1,…array2])]
console.log(“合并数组”,输出)
其他回答
您可以合并结果并过滤重复项:
let combinedItems = [];
// items is an Array of arrays: [[1,2,3],[1,5,6],...]
items.forEach(currItems => {
if (currItems && currItems.length > 0) {
combinedItems = combinedItems.concat(currItems);
}
});
let noDuplicateItems = combinedItems.filter((item, index) => {
return !combinedItems.includes(item, index + 1);
});
这是我需要合并(或返回两个数组的并集)时使用的函数。
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"]
首先连接两个数组,然后只过滤出唯一的项:
变量a=[1,2,3],b=[101,2,1,10]var c=交流电(b)var d=c.filter((项目,位置)=>c.indexOf(项目)===位置)console.log(d)//d为[1,2,3,101,10]
Edit
正如所建议的,一个更具性能的解决方案是在与a连接之前过滤掉b中的唯一项:
变量a=[1,2,3],b=[101,2,1,10]var c=a.oncat(b.filter((项)=>a.indexOf(项)<0))console.log(c)//c为[1,2,3,101,10]
新解决方案(使用Array.prototype.indexOf和Array.prototype.cocat):
Array.prototype.uniqueMerge = function( a ) {
for ( var nonDuplicates = [], i = 0, l = a.length; i<l; ++i ) {
if ( this.indexOf( a[i] ) === -1 ) {
nonDuplicates.push( a[i] );
}
}
return this.concat( nonDuplicates )
};
用法:
>>> ['Vijendra', 'Singh'].uniqueMerge(['Singh', 'Shakya'])
["Vijendra", "Singh", "Shakya"]
Array.prototype.indexOf(用于internet explorer):
Array.prototype.indexOf = Array.prototype.indexOf || function(elt)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from): Math.floor(from);
if (from < 0)from += len;
for (; from < len; from++)
{
if (from in this && this[from] === elt)return from;
}
return -1;
};
如果像我一样,您需要支持较旧的浏览器,这适用于IE6+
function es3Merge(a, b) {
var hash = {},
i = (a = a.slice(0)).length,
e;
while (i--) {
hash[a[i]] = 1;
}
for (i = 0; i < b.length; i++) {
hash[e = b[i]] || a.push(e);
}
return a;
};
http://jsperf.com/merge-two-arrays-keeping-only-unique-values/22