Programming
javascript arrays merge
Updated Sat, 23 Jul 2022 02:53:17 GMT

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


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?




Solution

To just merge the arrays (without removing duplicates)

ES5 version use Array.concat:

var array1 = ["Vijendra", "Singh"];
var array2 = ["Singh", "Shakya"];
array1 = array1.concat(array2);
console.log(array1);




Comments (5)

  • +0 – Note that this algorithm is O(n^2). — Oct 18, 2009 at 08:54  
  • +7 – Let [a, b, c] and [x, b, d] be the arrays (assume quotes). concat gives [a, b, c, x, b, d]. Wouldn't the unique()'s output be [a, c, x, b, d]. That doesn't preserve the order I think - I believe OP wants [a, b, c, x, d] — Oct 18, 2009 at 09:04  
  • +0 – I originally up-voted this but have changed my mind. Assigning prototypes to Array.prototype has the consequences of breaking "for ... in" statements. So the best solution is probably to use a function like this but not assign it as a prototype. Some people may argue that "for ... in" statements shouldn't be used to iterate array elements anyway, but people often use them that way so at the very least this solution be used with caution. — Feb 02, 2011 at 00:49  
  • +0 – you should always use for ... in with hasOwnProperty in which case the prototype method is fine — Jan 01, 2013 at 12:17  
  • +2 – Just use Babel and Set() as described in another answer. — May 04, 2016 at 20:32