我有两个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 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var mergedArrayWithoutDuplicates = array1.concat(
array2.filter(seccondArrayItem => !array1.includes(seccondArrayItem))
);
其他回答
合并两个阵列有很多解决方案。它们可以分为两大类(除了使用lodash或underline.js等第三方库)。
a) 组合两个数组并删除重复项。
b) 在组合项目之前过滤掉它们。
合并两个数组并删除重复项
结合
// mutable operation(array1 is the combined array)
array1.push(...array2);
array1.unshift(...array2);
// immutable operation
const combined = array1.concat(array2);
const combined = [...array1, ...array2]; // ES6
统一
统一数组有很多方法,我个人建议使用以下两种方法。
// a little bit tricky
const merged = combined.filter((item, index) => combined.indexOf(item) === index);
const merged = [...new Set(combined)];
在组合项目之前筛选出项目
还有很多方法,但我个人建议使用以下代码,因为它简单。
const merged = array1.concat(array2.filter(secItem => !array1.includes(secItem)));
用法: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;
}
在Dojo 1.6中+
var unique = [];
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = array1.concat(array2); // Merged both arrays
dojo.forEach(array3, function(item) {
if (dojo.indexOf(unique, item) > -1) return;
unique.push(item);
});
使现代化
参见工作代码。
http://jsfiddle.net/UAxJa/1/
新解决方案(使用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;
};
Use:
Array.prototype.merge = function (arr) {
var key;
for(key in arr)
this[key] = arr[key];
};