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);

2023 update

The original answer was from years ago. ES6 is fully supported and IE is finally dead. Here's the simplest way to merge primitive and object arrays:

const merge = (a, b, predicate = (a, b) => a === b) => {
    const c = [...a]; // copy to avoid side effects
    // add all items from B to copy C if they're not already present
    b.forEach((bItem) => (c.some((cItem) => predicate(bItem, cItem)) ? null : c.push(bItem)))
    return c;
}

merge(['a', 'b', 'c'], ['c', 'x', 'd']);
// => ['a', 'b', 'c', 'x', 'd']

merge([{id: 1}, {id: 2}], [{id: 2}, {id: 3}], (a, b) => a.id === b.id);
// [{id: 1}, {id: 2}, {id: 3}]

Original answer

ES6 version use destructuring

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

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. Note that this pollutes the Array prototype, use with caution.

Array.prototype.unique = function() {
    var a = this.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++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<a.length; ++i) {
        for(var j=i+1; j<a.length; ++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<a.length; ++i) {
            for(var j=i+1; j<a.length; ++j) {
                if(a[i] === a[j])
                    a.splice(j--, 1);
            }
        }

        return a;
    }
});
Answer from LiraNuna on Stack Overflow
Top answer
1 of 16
2350

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);

2023 update

The original answer was from years ago. ES6 is fully supported and IE is finally dead. Here's the simplest way to merge primitive and object arrays:

const merge = (a, b, predicate = (a, b) => a === b) => {
    const c = [...a]; // copy to avoid side effects
    // add all items from B to copy C if they're not already present
    b.forEach((bItem) => (c.some((cItem) => predicate(bItem, cItem)) ? null : c.push(bItem)))
    return c;
}

merge(['a', 'b', 'c'], ['c', 'x', 'd']);
// => ['a', 'b', 'c', 'x', 'd']

merge([{id: 1}, {id: 2}], [{id: 2}, {id: 3}], (a, b) => a.id === b.id);
// [{id: 1}, {id: 2}, {id: 3}]

Original answer

ES6 version use destructuring

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

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. Note that this pollutes the Array prototype, use with caution.

Array.prototype.unique = function() {
    var a = this.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++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<a.length; ++i) {
        for(var j=i+1; j<a.length; ++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<a.length; ++i) {
            for(var j=i+1; j<a.length; ++j) {
                if(a[i] === a[j])
                    a.splice(j--, 1);
            }
        }

        return a;
    }
});
2 of 16
665

With Underscore.js or Lo-Dash you can do:

console.log(_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

http://underscorejs.org/#union

http://lodash.com/docs#union

๐ŸŒ
Medium
medium.com โ€บ @rivoltafilippo โ€บ javascript-merge-arrays-without-duplicates-3fbd8f4881be
Javascript merge arrays without duplicates | by Filippo Rivolta | Medium
April 12, 2021 - Using ES5 we can merge the two input arrays without removing the duplicates with .concat() and then loop again through the result array and remove duplicates using indexOf.
๐ŸŒ
Envato Tuts+
code.tutsplus.com โ€บ home โ€บ coding fundamentals
Merge Arrays in JavaScript: With and Without Duplicates | Envato Tuts+
February 19, 2023 - concat() can be used to merge multiple arrays together, but it does not remove duplicates.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ how-to-merge-two-arrays-and-remove-duplicate-items-in-javascript
How to Merge Two Arrays and Remove Duplicate Items in JavaScript? - GeeksforGeeks
July 23, 2025 - // Given arrays let a1 = [10, 20, 30, 40]; let a2 = [30, 40, 50, 70]; // Use concat() methd to merge the arrays // and Set() to eliminate duplicates let s = new Set(a1.concat(a2)); // Convert the set back to an array let a = [...s]; // Display ...
Top answer
1 of 14
10

JavaScript O(N) 131 124 116 92 (86?)

Golfed version:

function m(i,x){h={};n=[];for(a=2;a--;i=x)i.map(function(b){h[b]=h[b]||n.push(b)});return n}

Human readable golfed version:

function m(i,x) {
   h = {}
   n = []
   for (a = 2; a--; i=x)
      i.map(function(b){
        h[b] = h[b] || n.push(b)
      })
   return n
}

I could use concat like so and do it in 86 characters:

function m(i,x){h={};n=[];i.concat(x).map(function(b){h[b]=h[b]||n.push(b)});return n}

But I am not sure if it is still O(N) based on this JsPerf: http://jsperf.com/unique-array-merging-concat-vs-looping as the concat version is marginally faster with smaller arrays but slower with larger arrays (Chrome 31 OSX).

In practice do this (golf is full of bad practices):

function merge(a1, a2) {
   var hash = {};
   var arr = [];
   for (var i = 0; i < a1.length; i++) {
      if (hash[a1[i]] !== true) {
        hash[a1[i]] = true;
        arr[arr.length] = a1[i];
      }
   }
   for (var i = 0; i < a2.length; i++) {
      if (hash[a2[i]] !== true) {
        hash[a2[i]] = true;
        arr[arr.length] = a2[i];
      }
   }
   return arr;
}
console.log(merge([1,2,3,4,5],[1,2,3,4,5,6]));

I'm not great at computing complexity but I believe this is O(N). Would love if someone could clarify.

Edit: Here is a version that takes any number of arrays and merges them.

function merge() {
   var args = arguments;
   var hash = {};
   var arr = [];
   for (var i = 0; i < args.length; i++) {
      for (var j = 0; j < args[i].length; j++) {
        if (hash[args[i][j]] !== true) {
          arr[arr.length] = args[i][j];
          hash[args[i][j]] = true;
        }
      }
    }
   return arr;
}
console.log(merge([1,2,3,4,5],[1,2,3,4,5,6],[1,2,3,4,5,6,7],[1,2,3,4,5,6,7,8]));
2 of 14
8

Perl

27 Characters

Simple Perl Hack

my @vals = ();
push @vals, @arr1, @arr2;
my %out;
map { $out{$_}++ } @vals;
my @unique = keys %out;

I'm sure someone could one-liner this.. and thus (Thanks Dom Hastings)

sub x{$_{$_}++for@_;keys%_}
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ javascript โ€บ examples โ€บ merge-two-arrays-and-remove-duplicate-items
JavaScript Program to Merge Two Arrays and Remove Duplicate Items | Vultr Docs
December 18, 2024 - Conceive first merging the arrays into a single array without any filtration. Utilize the concat() method or the spread operator to achieve this merge. ... const array1 = [1, 2, 3]; const array2 = [2, 3, 4, 5]; const combinedArray = ...
๐ŸŒ
Squash
squash.io โ€บ how-to-merge-arrays-and-remove-duplicates-in-javascript
How To Merge Arrays And Remove Duplicates In Javascript
In this approach, the concat method is used to merge the arrays, while the filter method is used to create a new array that only contains elements whose index matches their first occurrence in the merged array.
Find elsewhere
๐ŸŒ
Peterbe.com
peterbe.com โ€บ plog โ€บ merge-two-arrays-without-duplicates-in-javascript
Merge two arrays without duplicates in JavaScript - Peterbe.com
const array1 = [1, 2, 3]; const array2 = [2, 3, 4]; console.log([...new Set([...array1, ...array2])]); // prints [1, 2, 3, 4]
๐ŸŒ
Programiz
programiz.com โ€บ javascript โ€บ examples โ€บ merge-remove-duplicate
JavaScript Program to Merge Two Arrays and Remove Duplicate Items
To understand this example, you should have the knowledge of the following JavaScript programming topics: ... // program to merge and remove duplicate value from an array function getUniqueAfterMerge(arr1, arr2){ // merge two arrays let arr = arr1.concat(arr2); let uniqueArr = []; // loop through array for(let i of arr) { if(uniqueArr.indexOf(i) === -1) { uniqueArr.push(i); } } console.log(uniqueArr); } const array1 = [1, 2, 3]; const array2 = [2, 3, 5] // calling the function // passing array argument getUniqueAfterMerge(array1, array2);
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Array โ€บ concat
Array.prototype.concat() - JavaScript | MDN
The concat() method of Array instances is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ javascript โ€บ javascript merge arrays
How to Merge Two Arrays Without Any Duplicates in JavaScript | Delft Stack
February 2, 2024 - The prototype is like the Object associated with all functions and Objects in JavaScript. Letโ€™s see how we can use the Array.prototype. ... Create a nested loop to find and remove the duplicate element found using arr.splice(). The outer start from n and the inner from n+1. Array.prototype.removeDuplicates = function() { var arr = this.concat(); // create a clone from the input so not to change // the source // create the first cycle of the loop starting from element 0 or n for (var i = 0; i < arr.length; ++i) { // create the second cycle of the loop from element n+1 for (var j = i + 1; j < arr.length; ++j) { // if the two elements are equal , then they are duplicate if (arr[i] === arr[j]) { arr.splice(j, 1); // remove the duplicated element } } } return arr; }
๐ŸŒ
YouTube
youtube.com โ€บ watch
Javascript Tutorial to Merge Two Arrays and Remove Duplicate Items Using Spread Syntax and Concat - YouTube
Buy the full source code of application here:https://procodestore.com/index.php/product/javascript-tutorial-to-merge-two-arrays-and-remove-duplicate-items-us...
Published ย  October 15, 2021
๐ŸŒ
W3docs
w3docs.com โ€บ javascript
How to Merge Two Arrays in JavaScript and De-duplicate Items
This version uses the concat() ... changing the existing arrays, but returns a new array. To remove duplicates, the filter() method can be used:...
๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ javascript merge arrays without duplicates | example code
JavaScript merge arrays without duplicates | Example code
August 23, 2022 - <!DOCTYPE html> <html> <head> <script> const arr1 = [1, 2, 3]; const arr2 = [2, 3, 5]; // merge two arrays let arr = arr1.concat(arr2); let uniqueArr = []; // loop through array for(let i of arr) { if(uniqueArr.indexOf(i) === -1) { uniqueArr.push(i); } } console.log(uniqueArr); </script> </head> </html> ... The array is converted to Set and all the duplicate elements are automatically removed.
๐ŸŒ
Esri Community
community.esri.com โ€บ t5 โ€บ arcgis-javascript-maps-sdk-questions โ€บ merge-two-arrays โ€บ td-p โ€บ 623456
Solved: Merge two arrays - Esri Community
August 15, 2019 - Since there is no 'built in' way ... we have to do it manually: Array.prototype.unique = function() { var a = this.concat(); for(var i=0; i<a.length; ++i) { for(var j=i+1; j<a.length; ++j) { if(a[i] === a[j]) a.splice(j--, 1); } } return a;};...
๐ŸŒ
JavaScript in Plain English
javascript.plainenglish.io โ€บ merge-arrays-without-duplicates-in-javascript-and-an-analysis-of-their-pros-and-cons-32eead48185
Merge Arrays Without Duplicates in JavaScript and an Analysis of their Pros and Cons | by pandaquests | JavaScript in Plain English
January 26, 2023 - In this article, we will explore some of the most common methods for merging arrays without duplicates in JavaScript and analyze their pros and cons. From using the spread operator and filter method to using the Array.concat() method, we will discuss the efficiency, simplicity, and readability ...
๐ŸŒ
Clue Mediator
cluemediator.com โ€บ merging-two-arrays-without-any-duplicates-in-javascript
Merging Two Arrays Without Any Duplicates in JavaScript - Clue Mediator
Leveraging `concat()` and `filter()`: The Classic Approach ยท Using `reduce()`: The Custom Approach ยท Let's dive into different techniques to merge arrays without duplicates using JavaScript. JavaScript's built-in Set object is a powerful tool for handling unique values.