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?
This is an ECMAScript 6 solution using spread operator and array generics.
Currently it only works with Firefox, and possibly Internet Explorer Technical Preview.
But if you use Babel, you can have it now.
A much better array merge function.
You can achieve it simply using Underscore.js's => uniq:
It will print ["Vijendra", "Singh", "Shakya"].
for the sake of it... here is a single line solution:
Not particularly readable but it may help someone:
Set
.Set
to an array.sort()
function is applied to the new array.Just steer clear of nested loops (O(n^2)), and
.indexOf()
(+O(n)).