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?
To just merge the arrays (without removing duplicates)
ES5 version use
Array.concat
:ES6 version use destructuring
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:Then, to use it:
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
andfor in
loops, here is a less invasive way to use it:For those who are fortunate enough to work with browsers where ES5 is available, you can use
Object.defineProperty
like this:Just throwing in my two cents.
This is a method I use a lot, it uses an object as a hashlookup table to do the duplicate checking. Assuming that the hash is O(1), then this runs in O(n) where n is 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.
With Underscore.js or Lo-Dash you can do:
http://underscorejs.org/#union
http://lodash.com/docs#union
merge two arrays and remove duplicate in es6
ES6
OR
OR
Why don't you use an object? It looks like you're trying to model a set. This won't preserve the order, however.