如何合并两个数组中的Javascript和去重复项目 [英] How to merge two arrays in Javascript and de-duplicate items
问题描述
我有两个JavaScript数组:
I have two JavaScript arrays:
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.
如何合并在JavaScript中两个数组,这样我得到的只有来自同一顺序每个阵列唯一项目插入到原来的阵列?
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?
推荐答案
要合并只是阵列(不删除重复)使用 Array.concat
:
To just merge the arrays (without removing duplicates) use Array.concat
:
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = array1.concat(array2); // Merges both arrays
// [ 'Vijendra', 'Singh', 'Singh', 'Shakya' ]
由于没有内置的方式来删除重复( ECMA- 262 实际上有 Array.forEach
这将是伟大的..),所以我们做手工:
Since there is no 'built in' way to remove duplicate (ECMA-262 actually has Array.forEach
which would be great for this..), so we do it manually:
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();
这也将preserve阵列的顺序(即,不排序需要)。
This will also preserve the order of the arrays (i.e, no sorting needed).
编辑:
由于很多人都恼火的 Array.prototype
和在
循环原型增强,这里是一个不太侵入性的方式来使用它:
Since many people are annoyed about prototype augmentation of Array.prototype
and for in
loops, here is a less invasive way to use it:
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));
对于那些谁有幸与进步的浏览器兼容,其中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;
}
});
这篇关于如何合并两个数组中的Javascript和去重复项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!