How to merge two arrays in Javascript and de-duplicate items -
How to merge two arrays in Javascript and de-duplicate items -
i have 2 javascript arrays:
var array1 = ["vijendra","singh"]; var array2 = ["singh", "shakya"];
i want output be:
var array3 = ["vijendra","singh","shakya"];
the output array should have repeated words removed.
how merge 2 arrays in javascript unique items each array in same order inserted original arrays?
to merge arrays (without removing duplicates) utilize array.concat
:
var array1 = ["vijendra","singh"]; var array2 = ["singh", "shakya"]; var array3 = array1.concat(array2); // merges both arrays // [ 'vijendra', 'singh', 'singh', 'shakya' ]
since there no 'built in' way remove duplicate (ecma-262 has array.foreach
great this..), manually:
array.prototype.unique = function() { var = 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); } } homecoming a; };
then, utilize it:
var array1 = ["vijendra","singh"]; var array2 = ["singh", "shakya"]; // merges both arrays , gets unique items var array3 = array1.concat(array2).unique();
this preserve order of arrays (i.e, no sorting needed).
edit:
since many people annoyed prototype augmentation of array.prototype
, for in
loops, here less invasive way utilize it:
function arrayunique(array) { var = 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); } } homecoming a; } var array1 = ["vijendra","singh"]; var array2 = ["singh", "shakya"]; // merges both arrays , gets unique items var array3 = arrayunique(array1.concat(array2));
for fortunate plenty work progressive browsers es5 available, can utilize object.defineproperty
:
object.defineproperty(array.prototype, 'unique' { enumerable: false, configurable: false, writable: false, value: function() { var = 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); } } homecoming a; } });
javascript merge
Comments
Post a Comment