Как объединить массивы в 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()
Как мы видели ранее два предыдущих способа создают новый массив содержащий исходные, но иногда необходимо не создавать новый массив, а добавить один массив в другой. В этом случает один из исходных массивов будет изменен.
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.
The array concat method and some other ways of adding two arrays together
So there is adding two strings or numbers together with the addition operator in javaScript, but then there is adding two or more objects together including Arrays and how such an operation should be handled. In the array prototype object there is the array concat method that can be used to create a new array that is the concatenation of two or more arrays, or values by themselves actually. Simply put the Array.concat method is one way to go about adding two or more arrays together into a single array.
There are then also ways of going about doing the same thing, such as converting an array to a string and then back again using something like the array join, and then string split methods. There are also methods in popular utility libraries, such as the concat method in lodash and well as join and split methods. Another thing that comes to mind is what is really intended by adding two arrays together, typically that would be just creating a new array with the elements of one or more arrays, but in some cased one might want a sum of one or more arrays of numbers.
There are also a number of things to look out for when concatenating arrays together when it comes to the values in the arrays. For example when it comes to having to arrays of objects the resulting array will be a new array, but the objects in the arrays will still reference the same objects in memory. So lets look at some examples of array concatenation with the array concat method, as well as other ways to go about getting a similar effect.
1 — Basic array concat example
So the basic idea of the concat method is that I just call it off of an instance of a javaScript array, and then pass one or more arrays that I want to concatenate with the array that I call the method off of. A new array will be returned by the array concat method, and none of the source arrays including the array that the method is called off of will be mutated.
So then that is the basic idea of the array concat method, it is there for just going ahead and adding one array to another. When it comes to simple arrays or primitive values like this it will work just fine as expected. It is only when coping arrays of nested objects that maybe a developing might run into some problems though when it comes to copying references to objects, but maybe that is a matter for another post. In any case lets look at least a few more examples of adding two or more arrays together into one.
2 — Can pass arrays, and just values also as arguments
So the array concat method can be used to concatenate two or more arrays, but values can also be added via arguments also. So then this concat method also works as an alternative to the array push method then also on top of just a way to add to arrays together into one array.
speaking of the array push method it is actually possible to use array push in the same way as concat when it comes to just one array at least when it comes to using array push with something like the function apply method. More on that later in this post.
3 — Using array like objects and array concat
So with many array prototype methods it is possible to use the Function call prototype method to get an array method to work with array like objects. However when using the array concat method on an array like object with function call I end up getting a result that might not end up being expected. So when working with array like objects, it might be better to use the array from static method to convert an array like object to an array, and then use concat off of the resulting array.
4 — The addition operator, strings, and the string split method
So one might think that the addition operator can just be used to add to arrays together. The funny thing about it is that in some cases you actually can if we are talking about an array of primitive values at least maybe. When adding two arrays together by default the value of methods will return a string value of the array. So by adding a comma between the two arrays you might end up with a formatted string that can then be split back into an array.
In other words something like this:
I can not recommend that doing this is a good practice, but in some cases it seems to work okay, so I guess it is worth writing about at least. It is also worth mentioning the nature of valueOf and ToString methods of objects, and why they come in handy in some situations. When working with the addition of objects a toString method defines logic that will be used to create a string primitive value of the object, and the valueOf method can be used to define what a number primitive value is for the object. However maybe getting into the depth of that is a matter for other blog posts.
5 — Using array.push and Function.apply to concatenate arrays
Another way to concatenate arrays would be to use the array push method with the apply function prototype method. the thing about the push method is that it can be used to add one or more elements to an array, but only by way of one element at a time, or more than one but by way of two or more arguments when calling array push. So the apply function method can be called off of the push method, and the array that you to concatenate to can be passed as the first argument followed by the other array that you want at the end of the one given the first argument to apply.
The same should also work when it comes to using the array unshift method that is the same as push only it adds element to the beginning of an array rather than the end.
Apply, call and bind are worth writing more about, but I will not be getting into detail with those methods here. I have wrote a post on these methods before hand anyway a long time ago, so there is just reading over that post if you want my take on these methods. Yes they come in handy a lot when working with javaScript code, so you should take a moment to read up on them more if you have not done so all ready.
6 — Arrays of objects and copying by reference
When working with two arrays of objects it is a good idea to keep in mind that the Array.concat method, and many other ways of concatenating arrays will result in a new array, but the new array will be a shallow copy. A shallow copy, or clone if you prefer, is a new array, but any nested objects in the array as elements might still be references to the same objects in memory.
In many cases this might be what I want to happen actually, but in other cases I might want new objects in the resulting array. One way to do so would be to map over the array, and create a new object for each.
For more on this topic you might want to check out my post in which I get into the process of copying arrays in detail.
7 — Add arrays of numbers together
What if I want to add two arrays of numbers together, but add values rather than just append values to the end of a new array? So in order words I want to create a new array, but I want to add the corresponding values that have the same element index in each of them. Then there is also create a final sum of all the numbers in the form of a number rather than an array. So in this section I will be going over a quick source code example of this sort of thing when it comes to adding two arrays together.
8 — Conclusion
So the array concat method is the main goto method when it comes to creating a new array that is the product of two or more additional arrays. There is always more than one way of solving the same problem thous, not that any of the other methods of adding two or more arrays outline here are better choices or not though. It is generally a good idea to look into more than one way to go about doing something though, even if I end up just going with what it typical though.
Array.prototype.concat()
Метод concat() возвращает новый массив, состоящий из массива, на котором он был вызван, соединённого с другими массивами и/или значениями, переданными в качестве аргументов.
Интерактивный пример
Синтаксис
Параметры
Массивы и/или значения, соединяемые в новый массив. Смотрите описание ниже.
Возвращаемое значение
Описание
Метод concat создаёт новый массив, состоящий из элементов в объекте, на котором он был вызван, за которыми по порядку следуют, для каждого аргумента, все его элементы (если аргумент является массивом), либо сам аргумент (если он массивом не является).
Метод concat не изменяет данный массив или любой из массивов, переданных в аргументах, а вместо этого возвращает поверхностную копию, содержащую копии тех элементов, что были объединены с исходными массивами. Элементы оригинальных массивов копируются в новый массив по следующим правилам:
- Ссылки на объекты (но не фактические объекты): метод concat копирует ссылки на объекты в новый массив. И оригинал, и новый массив ссылаются на один и тот же объект. То есть, если объект по ссылке будет изменён, изменения будут видны и в новом, и в исходном массивах.
- Строки, числа и булевы значения (но не объекты String , Number или Boolean ): метод concat копирует значения строк и чисел в новый массив.
Примечание: Соединение массивов и/или значений в новый массив оставит соединяемые массивы/значения неизменными. Кроме того, любая операция над новым массивом (если только элемент не является ссылкой) не будет затрагивать исходные массивы и наоборот.