Saturday 23 December 2017

How to merge two arrays in JavaScript and de-duplicate items

itemprop="text">

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.



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?


itemprop="text">
class="normal">Answer



To just
merge the arrays (without removing
duplicates)




ES5 version use
Array.concat:



class="snippet" data-lang="js" data-hide="false" data-console="true"
data-babel="false">

class="snippet-code-js lang-js prettyprint-override">var array1 =
["Vijendra", "Singh"];
var array2 = ["Singh",
"Shakya"];

console.log(array1.concat(array2));






ES6
version use href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment"
rel="noreferrer">destructuring



const
array1 = ["Vijendra","Singh"];
const array2 = ["Singh",
"Shakya"];
const array3 = [...array1,
...array2];


Since
there is no 'built in' way to remove duplicates ( href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf"
rel="noreferrer">ECMA-262 actually has
Array.forEach which would be great for this), we have to do it
manually:




Array.prototype.unique
= function() {
var a = this.concat();
for(var i=0; i ++i) {
for(var j=i+1; 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 (i.e, 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:



function arrayUnique(array)
{
var a = array.concat();
for(var i=0; i {
for(var j=i+1; 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:



Object.defineProperty(Array.prototype,
'unique', {
enumerable: false,
configurable: false,

writable: false,

value: function() {
var a =
this.concat();
for(var i=0; i for(var j=i+1;
j if(a[i] === a[j])
a.splice(j--,
1);
}
}

return a;


}
});


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...