- doctor Brain
- Метод .concat()
- Оператор расширения
- Какой способ лучше?
- Новые публикации
- JavaScript: сохраняем страницу в pdf
- HTML: Полезные примеры
- CSS: Ускоряем загрузку страницы
- JavaScript: 5 странностей
- JavaScript: конструктор сортировщиков
- Категории
- О нас
- Как объединить массивы в JavaScript
- Способ 1 — объединение массивов через оператор spread
- Способ 2 — объединение массивов методом array.concat()
- Способ 3 — объединение массивов через метод array.push()
- Сергей Мочалов
- How to Merge Arrays in JavaScript – Array Concatenation in JS
- 1. How to Use the Spread Operator in JavaScript
- 2. How to Use Array.concat in JavaScript
- 3. How to Use Array.push in JavaScript
- Wrapping Up
doctor Brain
Объединение массивов, как в случае, когда оба массива уже существуют, так и в случае, когда один из массивов еще только будет создаваться, довольно распространенная задача. Тем не менее, поверхностный подход и несоблюдение определенных правил могут привести к тому, что полученный результат вовсе не будет соответствовать ожидаемому.
Итак, у нас есть два массива [1,2,3] и [4,5,6]. Резонно ожидать, что результатом их объединения будет массив [1,2,3,4,5,6]. Конечно, в первую очередь хочется использовать оператор сложения (+) или метод .push(), но ни один из этих способов не приведет к желаемому результату:
a = [1,2,3] b = [4,5,6] console.log(a + b); // [1,2,34,5,6] console.log(a.push(b)); // [1,2,3,[4,5,6]]
В первом случае, при использовании оператора +, каждая переменная приведется к строке и выполнится конкатенация. В результате, последний элемент массива а — 3, и первый элемент массива b — 4 объединятся в значение 34.
Во втором случае, при использовании метода .push(), переменная b станет последним элементом массива a. То есть последним элементом массива a будет массив b.
Для корректного объединения массивов нужно использовать метод .concat() или оператор расширения . .
Метод .concat()
Де-факто, это уже давно стандартный способ объединения массивов. При этом первый массив является родительским. К нему и применяется метод .concat(), позволяя объединить любое количество массивов.
let a = [1,2,3]; let b = [4,5,6]; let c = a.concat(b); console.log(c); // [1,2,3,4,5,6]
Оператор расширения
Поддерживается, начиная с ES6 и в более младших версиях. Оператор расширения “распаковывает” элементы исходного массива, включая элементы нескольких массивов в один новый массив:
let a = [1,2,3]; let b = [4,5,6]; let c = [. a, . b]; console.log(c);
Какой способ лучше?
Это интересный вопрос. Существует мнение, что правильный ответ зависит от статусов исходных массивов.
Тем не менее, использование оператора расширения выглядит более гибким и предпочтительным, особенно, когда в массивы необходимо вносить дальнейшие изменения. Метод .concat() можно использовать только при явной необходимости.
Например, что произойдет, если теперь нам нужно не только объединить массивы [1,2,3] и [4,5,6], но и добавить в самое начало массив [0,0,0]? Можно видеть, что использование оператора расширения смотрится лучше:
let a = [1,2,3]; let b = [4,5,6]; let c = [0,0,0].concat(a,b); let d = [0,0,0. a. b];
Для метода .concat() нам приходится использовать два атрибута и устанавливать в качестве родительского массива [0,0,0].
В случае с оператором расширения достаточно добавить в начало новые элементы массива.
Новые публикации
JavaScript: сохраняем страницу в pdf
HTML: Полезные примеры
CSS: Ускоряем загрузку страницы
JavaScript: 5 странностей
JavaScript: конструктор сортировщиков
Категории
О нас
Frontend & Backend. Статьи, обзоры, заметки, код, уроки.
© 2021 dr.Brain .
мир глазами веб-разработчика
Как объединить массивы в JavaScript
Массивы по своей сути это структура данных, представляющая упорядоченную коллекцию индексированных элементов.
И довольно часто в практике возникает необходимость объединения массивов — когда два и более отдельных массивов превращаются в большой массив содержащий все элементы первоначальных массивов.
Например объединение массива [1,2] и [5,6] приведет к появлению массива [1,2,5,6]
Мы рассмотрим три способа объединить массивы в JavaScript: 2 иммутабельных (новый массив создается после объединения)
Способ 1 — объединение массивов через оператор spread
Если вам нужен один хороший способ объединения массивов в JavaScript, тогда оператор spread — ваш выбор.
Напишите внутри массива две или более переменных с префиксом в виде spread оператора . и JavaScript объединит их в один новый массив. Собственно синтаксис:
const result = [. array1, . array2];
Как пример предположим у нас есть два массива содержащих фамилии студентов students1 и students2
const students1 = ['Иванов', 'Сидоров']; const students2 = ['Петров', 'Курочкина']; const all = [. students1, . students2]; all; // ['Иванов', 'Сидоров', 'Петров', 'Курочкина']
const all = [. students1, . students2] создает новый массив содержащий элементы исходных массивов students1 и students2
Порядок в котором вы перечисляете массивы при помощи оператора spread имеет значение! Элементы массива вставляются в том порядке в котором идут переменные этих массивов.
В нашем примере поменяем порядок:
const students1 = ['Иванов', 'Сидоров']; const students2 = ['Петров', 'Курочкина']; const all = [. students2, . students1]; all; // ['Петров', 'Курочкина', 'Иванов', 'Сидоров']
Spread оператор позволяет объединять 2 и более массивов:
const newArray = [. array1, . array2, . array3, . arrayN];
Способ 2 — объединение массивов методом array.concat()
Если вы предпочитаете функциональные методы объединения массивов, то можете использовать array1.concat(array2) метод:
const newArray = array1.concat(array2);
const newArray = [].concat(array1, array2);
array.concat() не изменяет исходные массивы, а формирует новый имеющий в составе элементы объединяемых массивов.
Давайте попробуем повторить пример из первого способа:
const students1 = ['Иванов', 'Сидоров']; const students2 = ['Петров', 'Курочкина']; const all_1 = students1.concat(students2); const all_2 = [].concat(students1,students2); all_1; // ['Иванов', 'Сидоров', 'Петров', 'Курочкина'] all_2; // ['Иванов', 'Сидоров', 'Петров', 'Курочкина']
Метод concat позволяет объединять более двух массивов:
const newArray = [].concat(array1, array2, array3, arrayN);
Способ 3 — объединение массивов через метод array.push()
Как мы видели ранее два предыдущих способа создают новый массив содержащий исходные, но иногда необходимо не создавать новый массив, а добавить один массив в другой. В этом случает один из исходных массивов будет изменен.
Вы наверняка знаете что метод array.push(item) добавляет к имеющемуся массиву новый элемент и ставит его в конец массива.
const students = ['Иванов']; students.push('Сидоров'); students; // ['Иванов', 'Сидоров']
Благодаря тому факту что array.push(item1, item2, . itemN) может принимать множественное количество элементов, мы можем запушить целый массив через оператор spread примененный к аргументу:
И если брать пример с нашими студентами то получим:
const students1 = ['Иванов', 'Сидоров']; const students2 = ['Петров', 'Курочкина']; students1.push(. students2); students1; // ['Иванов', 'Сидоров', 'Петров', 'Курочкина']
А какой из способов используете вы? Поделитесь в комментариях
Сергей Мочалов
Веб-разработчик. Создаю и поддерживаю сайты для клиентов с 2009 года
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.
const array1 = [1, 2, 3] const array2 = [4, 5, 6] const merged = [. array1, . array2] // [1, 2, 3, 4, 5, 6]
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:
const array1 = [1, 2, 3] const array2 = [4, 5, 6] const array3 = [7, 8, 9] const merged = [. array2, . array3, . array1] // [4, 5, 6, 7, 8, 9, 1, 2, 3]
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:
array.concat(value1, value2, . valueN)
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:
const array1 = [1, 2, 3] const array2 = [4, 5, 6] const merged = array1.concat(array2) // [1, 2, 3, 4, 5, 6]
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:
const array1 = [1, 2, 3] const array2 = [4, 5, 6] const array3 = [7, 8, 9] const merged = array2.concat(array3, array1) // [4, 5, 6, 7, 8, 9, 1, 2, 3]
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.
array.push(value1, value2, . valueN)
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.
const array1 = [1, 2, 3] const array2 = [4, 5, 6] for(let i = 0; i < array2.length; i++) < array1.push(array2[i]) >console.log(array1) // [1, 2, 3, 4, 5, 6]
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:
const array1 = [1, 2, 3] const array2 = [4, 5, 6] array1.push(. array2) console.log(array1) // [1, 2, 3, 4, 5, 6]
You can do this for multiple arrays:
const array1 = [1, 2, 3] const array2 = [4, 5, 6] const array3 = [7, 8, 9] array3.push(. array2, . array1) console.log(array3) // [7, 8, 9, 4, 5, 6, 1, 2, 3]
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.
Dillion Megida
Developer Advocate and Content Creator passionate about sharing my knowledge on Tech. I simplify JavaScript / ReactJS / NodeJS / Frameworks / TypeScript / et al My YT channel: youtube.com/c/deeecode
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.