我有两个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中合并两个数组,以便从每个数组中只获得唯一的项目,其顺序与它们插入原始数组的顺序相同?
当前回答
Array.prototype.pushUnique = function(values)
{
for (var i=0; i < values.length; i++)
if (this.indexOf(values[i]) == -1)
this.push(values[i]);
};
Try:
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
array1.pushUnique(array2);
alert(array1.toString()); // Output: Vijendra,Singh,Shakya
其他回答
使用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
这是我需要合并(或返回两个数组的并集)时使用的函数。
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"]
这是我的第二个答案,但我相信最快的答案是什么?我希望有人帮我检查并在评论中回复。
我的第一次尝试达到了99k操作/秒,这一次的复测是390k操作/每秒,而另一次领先的jsperf测试是140k(对我来说)。
http://jsperf.com/merge-two-arrays-keeping-only-unique-values/26
这次我尝试尽可能减少阵列交互,看起来我获得了一些性能。
function findMerge(a1, a2) {
var len1 = a1.length;
for (var x = 0; x < a2.length; x++) {
var found = false;
for (var y = 0; y < len1; y++) {
if (a2[x] === a1[y]) {
found = true;
break;
}
}
if(!found){
a1.push(a2.splice(x--, 1)[0]);
}
}
return a1;
}
编辑:我对我的功能做了一些更改,与jsperf站点上的其他功能相比,性能非常出色。
使用reduce func查看的另一种方法:
function mergeDistinct(arResult, candidate){
if (-1 == arResult.indexOf(candidate)) {
arResult.push(candidate);
}
return arResult;
}
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var arMerge = [];
arMerge = array1.reduce(mergeDistinct, arMerge);
arMerge = array2.reduce(mergeDistinct, arMerge);//["Vijendra","Singh","Shakya"];
用法:https://gist.github.com/samad-aghaei/7250ffb74ed80732debb1cbb14d2bfb0
var _uniqueMerge = function(opts, _ref){
for(var key in _ref)
if (_ref && _ref[key] && _ref[key].constructor && _ref[key].constructor === Object)
_ref[key] = _uniqueMerge((opts ? opts[key] : null), _ref[key] );
else if(opts && opts.hasOwnProperty(key))
_ref[key] = opts[key];
else _ref[key] = _ref[key][1];
return _ref;
}