1996

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?

2
  • 33
    Before you post a new answer, consider there are already 75+ answers for this question. Please, make sure that your answer contributes information that is not among existing answers.
    – janniks
    Commented Feb 3, 2020 at 12:05
  • If you want a more generic solution that also covers deep-merging, take a look at this question, instead. Some answers cover arrays as well. Commented May 6, 2020 at 13:06

91 Answers 91

1 2 3
4
-3

Use:

Array.prototype.merge = function (arr) {
    var key;
    for(key in arr) 
        this[key] = arr[key];
};
2
  • 1
    This doesn't merge arrays—this just overwrites one with another. E.g., var f = [1]; f.merge([2]);
    – Ian Hunter
    Commented Dec 30, 2013 at 23:20
  • Hmmm... but I thought the keys that are already there stay, and you want the new ones and the merged one to overwrite? Oh maybe I was thinking dictionaries or something. Commented Apr 15, 2015 at 13:08
1 2 3
4

Not the answer you're looking for? Browse other questions tagged or ask your own question.