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));
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;
}
});