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
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › concat
Array.prototype.concat() - JavaScript | MDN
Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property Symbol.isConcatSpreadable set to a truthy value, each element of the argument will be independently added to the final array.
🌐
W3Schools
w3schools.com › jsref › jsref_concat_array.asp
JavaScript Array concat() Method
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST ... Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean
🌐
Mimo
mimo.org › glossary › javascript › array-concatenation
JavaScript Array Concatenate: Syntax, Usage, and Examples
The two most common and recommended ways to concatenate arrays in JavaScript are the concat() method and the spread operator (...). Both create a new array without changing the original arrays.
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

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-array-concat-method
JavaScript Array concat() Method - GeeksforGeeks
[Example 1]: Below the Array concat() method to join three arrays. JavaScript ·
Published   December 30, 2017
🌐
Dmitri Pavlutin
dmitripavlutin.com › javascript-merge-arrays
3 Ways to Merge Arrays in JavaScript
January 28, 2023 - JavaScript offers multiple ways to merge arrays. You can use either the spread operator [...array1, ...array2], or a functional way [].concat(array1, array2) to merge 2 or more arrays.
🌐
TutorialsPoint
tutorialspoint.com › home › javascript › javascript array concat method
JavaScript Array concat Method
September 1, 2008 - JavaScript Array concat() Method one,two,three,four,five,six · In this example, we are concatenating more than two JavaScript arrays −
🌐
SamanthaMing
samanthaming.com › tidbits › 49-2-ways-to-merge-arrays
2 Ways to Merge Arrays in JavaScript | SamanthaMing.com
Here are 2 ways to combine your arrays and return a NEW array. I like using the Spread operator. But if you need older browser support, you should use Concat.
Find elsewhere
🌐
TechOnTheNet
techonthenet.com › js › array_concat.php
JavaScript: Array concat() method
var totn_array1 = ['Tech','On']; var totn_array2 = ['The','Net']; console.log(totn_array1.concat(totn_array2)); In this example, we have declared two array objects called totn_array1 and totn_array2, each with 2 elements.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript array methods › array.prototype.concat()
JavaScript Array concat: Merge Arrays
November 6, 2024 - ... let odds = [1, 3, 5]; let evens = [2, 4, 6]; let results = [].concat(odds, evens); console.log({ results });Code language: JavaScript (javascript) ... let upper = ['A', 'B', 'C']; let lower = ['a', 'b', 'c']; let digits = [1, 2, 3]; let ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › join
Array.prototype.join() - JavaScript | MDN
The join() method of Array instances creates and returns a new string by concatenating all of the elements in this array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › Array › concat
JavaScript Array concat() - Merge Arrays Together | Vultr Docs
November 28, 2024 - The resulting array is ['apple', 'banana', 'cherry', 'date']. Understand that concat() can merge more than two arrays at a time.
🌐
Programiz
programiz.com › javascript › library › array › concat
JavaScript Array concat()
[ 'JavaScript', 'Python', 'Java', 'C', 'C++' ] [ 'C', 'C++', 'Lua', 'JavaScript', 'Python', 'Java' ] The concat() method returns the shallow copy of the concatenated elements in the following way: It copies object references to the new array. (For example: passing a nested array) So if the referenced object is modified, the changes are visible in the returned new array.
🌐
Codedamn
codedamn.com › news › javascript
JavaScript concat array explained – How to merge arrays in JS
June 24, 2023 - In this example, array1 contains three numbers, while array2 contains three strings. The JavaScript concat() method is used to merge two or more arrays into a single array.
Top answer
1 of 2
13

JavaScript engines typically put a cap on the number of arguments you can pass to a method before they throw an error, for example, the below throws an error in Chrome:

const arr = Array(150000).fill(0);
const arr2 = [];
arr2.push(...arr);

Whereas when using .concat(), you'll only be passing the one array to the method, so you don't get the error:

const arr = Array(150000).fill(0);
const arr2 = [];
const res = arr2.concat(arr);
// res is an array with 150000 `0`s

Additionally, with .push() + ..., you're effectively doing two iterations over your iterable/array, one for unpacking its contents as arguments to the .push() method, and then another for one done internally by the .push() method itself to iterate through each of the arguments and append it to the target array.

Another noticeable difference is in what both methods return, .concat() will return a new array and won't modify the target, which can be useful in methods such as .map() or .reduce() where you need to produce a new array without mutating the original. Whereas .push() will return the length of the updated array and will modify the target, so that is another difference to consider.

As pointed out by @T.J. Crowder, the iterator of arrays which is invoked when using the spread syntax ... does not preserve blanks in sparse arrays, instead it unpacks them as undefined values, meaning that if the array you're specifying is sparse when using .push() + ... you'll get undefined for the blanks, whereas the blanks will be preserved when using .concat() directly:

const arr = Array(3); // this is a sparse array, [empty × 3], not to be confused with [undefined, undefined, undefined]
const arr2 = [];
arr2.push(...arr); // Here `...` becomes: arr2.push(undefined, undefined, undefined);
console.log(arr2); // [undefined, undefined, undefined]

const arr3 = [];
console.log(arr3.concat(arr)); // Retains empties: [empty × 3]
See browser console for results

2 of 2
0

I don't understand if you want to add an Array into another or just make one Array made of two Arrays.

In the last case this is a short way to concatenate Arrays too by using spread syntax:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combinedArray = [...arr1, ...arr2];
console.log(combinedArray);

Note:

If you need to preserve the original arrays, this code above is suitable, like the concat() method.

The push() method will modify your initial Array.

🌐
W3Resource
w3resource.com › javascript › object-property-method › array-concat.php
JavaScript concat() Method : Array Object - w3resource
Implemented in JavaScript 1.2 · ... be joined to an array. Example -1: In the following web document two arrays arrayname1 and arrayname2 with single element have joined by concat() method....
🌐
Greenroots
blog.greenroots.info › 5-ways-to-merge-arrays-in-javascript-and-their-differences
5 ways to merge arrays in JavaScript and their differences
October 15, 2021 - If you are sure the inputs are all arrays, please use the spread operator. It is a very straightforward and modern way to merge arrays. But if you are unsure about the input element type, use the concat() method. For example, let's take a string tapas and use the spread operator on it with the array literals,
🌐
Marius Schulz
mariusschulz.com › blog › concatenating-arrays-in-javascript
Concatenating Arrays in JavaScript — Marius Schulz
May 1, 2021 - Using spread syntax again, we can spread all elements of arrays as arguments into the concat() method call: ... Notice that we're creating an empty array here so that we can call the concat() method on it. Since it doesn't contain any elements, the empty array doesn't change the resulting concatenated array.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-merge-arrays-in-javascript-array-concatenation-in-js
How to Merge Arrays in JavaScript – Array Concatenation in JS
November 28, 2022 - By Dillion Megida There are multiple ways to merge arrays in JavaScript. You can use long or short approaches. I'll be showing 3 of them in this article. When working with arrays in JavaScript, there are cases where you want to combine multiple array...
🌐
Dillion's Blog
dillionmegida.com › p › array-concat
Array concat method simplified - Dillion's Blog
#javascript · Here's a video if you'd prefer that: https://youtu.be/a5kkO4KMvUE · The concat method in JavaSript is used to concatenate the contents of an existing array with new values to form a new array. I'll explain, with examples, how this method works on different values.