本文翻译自:How to merge two arrays in JavaScript and de-duplicate items
I have two JavaScript arrays: 我有两个JavaScript数组:
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
I want the output to be: 我希望输出为:
var array3 = ["Vijendra","Singh","Shakya"];
The output array should have repeated words removed. 输出数组应删除重复的单词。
How do I merge two arrays in JavaScript so that I get only the unique items from each array in the same order they were inserted into the original arrays? 如何在JavaScript中合并两个数组,以使每个数组中的唯一项按插入原始数组中的相同顺序获得?
#1楼
参考:https://stackoom.com/question/6eAM/如何在JavaScript中合并两个数组并删除重复项
#2楼
With Underscore.js or Lo-Dash you can do: 使用Underscore.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://underscorejs.org/#union
http://lodash.com/docs#union http://lodash.com/docs#union
#3楼
Just throwing in my two cents. 只需投入我的两分钱。
function mergeStringArrays(a, b){
var hash = {};
var ret = [];
for(var i=0; i < a.length; i++){
var e = a[i];
if (!hash[e]){
hash[e] = true;
ret.push(e);
}
}
for(var i=0; i < b.length; i++){
var e = b[i];
if (!hash[e]){
hash[e] = true;
ret.push(e);
}
}
return ret;
}
This is a method I use a lot, it uses an object as a hashlookup table to do the duplicate checking. 这是我经常使用的一种方法,它使用一个对象作为hashlookup表来进行重复检查。 Assuming that the hash is O(1), then this runs in O(n) where n is a.length + b.length. 假设哈希为O(1),则此哈希在O(n)中运行,其中n为a.length + b.length。 I honestly have no idea how the browser does the hash, but it performs well on many thousands of data points. 老实说,我不知道浏览器如何进行哈希处理,但是它在成千上万个数据点上表现良好。
#4楼
New solution ( which uses Array.prototype.indexOf
and Array.prototype.concat
): 新解决方案(使用Array.prototype.indexOf
和Array.prototype.concat
):
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 )
};
Usage: 用法:
>>> ['Vijendra', 'Singh'].uniqueMerge(['Singh', 'Shakya'])
["Vijendra", "Singh", "Shakya"]
Array.prototype.indexOf ( for internet explorer ): 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;
};
#5楼
To just merge the arrays (without removing duplicates) 仅合并数组(不删除重复项)
ES5 version use Array.concat
: ES5版本使用Array.concat
:
var array1 = ["Vijendra", "Singh"]; var array2 = ["Singh", "Shakya"]; console.log(array1.concat(array2));
ES6 version use destructuring ES6版本使用解构
const array1 = ["Vijendra","Singh"];
const array2 = ["Singh", "Shakya"];
const array3 = [...array1, ...array2];
Since there is no 'built in' way to remove duplicates ( ECMA-262 actually has Array.forEach
which would be great for this), we have to do it manually: 由于没有“内置”方式来删除重复项( ECMA-262实际上具有Array.forEach
对此非常Array.forEach
),因此我们必须手动执行此操作:
Array.prototype.unique = function() {
var a = this.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
};
Then, to use it: 然后,使用它:
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
// Merges both arrays and gets unique items
var array3 = array1.concat(array2).unique();
This will also preserve the order of the arrays (ie, no sorting needed). 这也将保留数组的顺序(即无需排序)。
Since many people are annoyed about prototype augmentation of Array.prototype
and for in
loops, here is a less invasive way to use it: 由于许多人都对Array.prototype
原型扩展和for in
循环感到烦恼,因此这是一种侵入性较小的使用方式:
function arrayUnique(array) {
var a = array.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
}
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
// Merges both arrays and gets unique items
var array3 = arrayUnique(array1.concat(array2));
For those who are fortunate enough to work with browsers where ES5 is available, you can use Object.defineProperty
like this: 对于那些幸运地使用ES5的浏览器的人,可以使用Object.defineProperty
如下所示:
Object.defineProperty(Array.prototype, 'unique', {
enumerable: false,
configurable: false,
writable: false,
value: function() {
var a = this.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
}
});
#6楼
//Array.indexOf was introduced in javascript 1.6 (ECMA-262)
//We need to implement it explicitly for other browsers,
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt, from)
{
var len = this.length >>> 0;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
//now, on to the problem
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var merged = array1.concat(array2);
var t;
for(i = 0; i < merged.length; i++)
if((t = merged.indexOf(i + 1, merged[i])) != -1)
{
merged.splice(t, 1);
i--;//in case of multiple occurrences
}
Implementation of indexOf
method for other browsers is taken from MDC 其他浏览器的indexOf
方法的实现来自MDC