- Как объединить массивы в JavaScript
- Способ 1 — объединение массивов через оператор spread
- Способ 2 — объединение массивов методом array.concat()
- Способ 3 — объединение массивов через метод array.push()
- Сергей Мочалов
- Array.prototype.concat()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Concatenating two arrays
- Concatenating three arrays
- Concatenating values to an array
- Concatenating nested arrays
- Concatenating array-like objects with Symbol.isConcatSpreadable
- Using concat() on sparse arrays
- Calling concat() on non-array objects
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
Как объединить массивы в 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 года
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
concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN)
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
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.
Examples
Concatenating two arrays
The following code concatenates two arrays:
const letters = ["a", "b", "c"]; const numbers = [1, 2, 3]; const alphaNumeric = letters.concat(numbers); console.log(alphaNumeric); // results in ['a', 'b', 'c', 1, 2, 3]
Concatenating three arrays
The following code concatenates three arrays:
const num1 = [1, 2, 3]; const num2 = [4, 5, 6]; const num3 = [7, 8, 9]; const numbers = num1.concat(num2, num3); console.log(numbers); // results in [1, 2, 3, 4, 5, 6, 7, 8, 9]
Concatenating values to an array
The following code concatenates three values to an array:
const letters = ["a", "b", "c"]; const alphaNumeric = letters.concat(1, [2, 3]); console.log(alphaNumeric); // results in ['a', 'b', 'c', 1, 2, 3]
Concatenating nested arrays
The following code concatenates nested arrays and demonstrates retention of references:
const num1 = [[1]]; const num2 = [2, [3]]; const numbers = num1.concat(num2); console.log(numbers); // results in [[1], 2, [3]] // modify the first element of num1 num1[0].push(4); console.log(numbers); // results in [[1, 4], 2, [3]]
Concatenating array-like objects with Symbol.isConcatSpreadable
concat does not treat all array-like objects as arrays by default — only if Symbol.isConcatSpreadable is set to a truthy value (e.g. true ).
const obj1 = 0: 1, 1: 2, 2: 3, length: 3 >; const obj2 = 0: 1, 1: 2, 2: 3, length: 3, [Symbol.isConcatSpreadable]: true >; console.log([0].concat(obj1, obj2)); // [ 0, < '0': 1, '1': 2, '2': 3, length: 3 >, 1, 2, 3 ]
Using concat() on sparse arrays
If any of the source arrays is sparse, the resulting array will also be sparse:
.log([1, , 3].concat([4, 5])); // [1, empty, 3, 4, 5] console.log([1, 2].concat([3, , 5])); // [1, 2, 3, empty, 5]
Calling concat() on non-array objects
If the this value is not an array, it is converted to an object and then treated in the same way as the arguments for concat() . In this case the return value is always a plain new array.
.log(Array.prototype.concat.call(>, 1, 2, 3)); // [<>, 1, 2, 3] console.log(Array.prototype.concat.call(1, 2, 3)); // [ [Number: 1], 2, 3 ] const arrayLike = [Symbol.isConcatSpreadable]: true, length: 2, 0: 1, 1: 2, 2: 99, // ignored by concat() since length is 2 >; console.log(Array.prototype.concat.call(arrayLike, 3, 4)); // [1, 2, 3, 4]
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jun 27, 2023 by MDN contributors.
Your blueprint for a better internet.