Как объединить массивы в JavaScript

Массивы по своей сути это структура данных, представляющая упорядоченную коллекцию индексированных элементов.
И довольно часто в практике возникает необходимость объединения массивов — когда два и более отдельных массивов превращаются в большой массив содержащий все элементы первоначальных массивов.
Например объединение массива [1,2] и [5,6] приведет к появлению массива [1,2,5,6]
Мы рассмотрим три способа объединить массивы в JavaScript: 2 иммутабельных (новый массив создается после объединения)
Способ 1 — объединение массивов через оператор spread
Если вам нужен один хороший способ объединения массивов в JavaScript, тогда оператор spread — ваш выбор.
Напишите внутри массива две или более переменных с префиксом в виде spread оператора . и JavaScript объединит их в один новый массив. Собственно синтаксис:
Как пример предположим у нас есть два массива содержащих фамилии студентов students1 и students2
const all = [. students1, . students2] создает новый массив содержащий элементы исходных массивов students1 и students2
Порядок в котором вы перечисляете массивы при помощи оператора spread имеет значение! Элементы массива вставляются в том порядке в котором идут переменные этих массивов.
В нашем примере поменяем порядок:
Spread оператор позволяет объединять 2 и более массивов:
Способ 2 — объединение массивов методом array.concat()
Если вы предпочитаете функциональные методы объединения массивов, то можете использовать array1.concat(array2) метод:
или в другом варианте
array.concat() не изменяет исходные массивы, а формирует новый имеющий в составе элементы объединяемых массивов.
Давайте попробуем повторить пример из первого способа:
Метод concat позволяет объединять более двух массивов:
Способ 3 — объединение массивов через метод array.push()
Как мы видели ранее два предыдущих способа создают новый массив содержащий исходные, но иногда необходимо не создавать новый массив, а добавить один массив в другой. В этом случает один из исходных массивов будет изменен.
# Processing Multiple Arrays Together
array_merge overwrites the values of the first array with the values of the second array, if it cannot renumber the index.
You can use the + operator to merge two arrays in a way that the values of the first array never get overwritten, but it does not renumber numeric indexes, so you lose values of arrays that have an index that is also used in the first array.
# Array intersection
The array_intersect function will return an array of values that exist in all arrays that were passed to this function.
Array keys are preserved. Indexes from the original arrays are not.
array_intersect only check the values of the arrays. array_intersect_assoc function will return intersection of arrays with keys.
array_intersect_key function only check the intersection of keys. It will returns keys exist in all arrays.
# Changing a multidimensional array to associative array
If you have a multidimensional array like this:
And you want to change it to an associative array like this:
You can use this code:
Or, you can skip setting $associativeArrayKeys and $associativeArrayValues and use this simple one liner:
# Combining two arrays (keys from one, values from another)
The following example shows how to merge two arrays into one associative array, where the key values will be the items of the first array, and the values will be from the second:
How to Merge Arrays in JavaScript – Array Concatenation in JS

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 arrays together. For example, arrays with related data coming from different sources can be merged into one single array.
You can merge arrays in different ways. Let’s look at some of them, from my favorite to my least favorite.
Here’s a video version of this article if you’d like to use it to supplement your learning.
1. How to Use the Spread Operator in JavaScript
The spread operator allows you to spread an iterable collection (object or array) into another collection. Using this operator on arrays, you can merge the contents of arrays together.
Here’s an example:
For the merged variable, we create a new array and then spread the values of array1 followed by array2 in it. Now you can see the merged array containing the values from these arrays.
You can use this operator for multiple arrays:
In the merged array here, we first spread array2 , then array3 , and lastly, array1 .
You can learn more about this operator in this article: Spread Operator Simplified.
2. How to Use Array.concat in JavaScript
You use the concat method of arrays to combine the contents of an array with new values to form a new array.
These new values can be numbers, strings, booleans, objects, or even, arrays.
The method accepts a list of values as arguments:
By specifying an array as an argument, you can merge an existing array with the specified array to form a new array. Here’s an example:
As you can see, the contents of array1 are concatenated with the contents of array2 to form a new array assigned to merged .
You can pass multiple arrays for merging also:
In this example, we use the concat method on array2 which means the contents of array2 are first in the merged array.
For the arguments, we pass array3 first, which means the contents of array3 are next in the merged array, then followed by the contents of array1 .
You can learn more about concat in this article: Array concat simplified.
3. How to Use Array.push in JavaScript
The push method of arrays allows you to «push» (add) new values to the end of an array.
Using this method, you can push a new array to an existing array to create a merge process. Unlike the previous approaches I mentioned, the push approach modifies the array it is used on.
Here’s an example:
Here, we use a for loop to loop through the values of array2 , and on each loop, we push the value at the index to array1 .
At the end of the loop, you see array1 modified, containing the values from array2 .
Instead of a for loop, you can also use the spread operator with the push method. Since the push method accepts a list or arguments separated by a comma, you can spread another array in this method, and they will all be pushed to the array the method is applied to:
You can do this for multiple arrays:
Here, we call push on array3 , then spread the values of array2 followed by array1 as arguments to be pushed into array3 .
Wrapping Up
In this article, we’ve seen three approaches for merging arrays in JavaScript. I especially love the spread operator as it’s easier and simpler to use.
When using push , beware, as I mentioned, that it modifies the array it is used on (unlike concat that returns a new array instead). This can cause unexpected results if you do not use it intentionally and carefully.
Array.prototype.concat()
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
Try it
Syntax
Parameters
Arrays and/or values to concatenate into a new array. If all valueN parameters are omitted, concat returns a shallow copy of the existing array on which it is called. See the description below for more details.
Return value
A new Array instance.
Description
The concat method creates a new array. The array will first be populated by the elements in the object on which it is called. 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. The concat method does not recurse into nested array arguments.
The concat() method is a copying method. It does not alter this or any of the arrays provided as arguments but instead returns a shallow copy that contains the same elements as the ones from the original arrays.
The concat() method preserves empty slots if any of the source arrays is sparse.
The concat() method is generic. The this value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy @@isConcatSpreadable will be spread into the resulting array.