Javascript массив присвоить массиву

JavaScript | Как добавить массив внутрь другого массива?

Мы хотим добавить новый массив [55, 55] внутрь оригинального массива, чтобы сохранились все элементы. Как это сделать?

В какое место добавить( вставить ) новый массив?

Существует всего 3 варианта куда мы можем запихнуть новый массив:

Рассмотрим все 3 варианта реализации. Нам нужно воспользоваться методом splice() для объектов-прототипов Array .

Как добавить массив в начало другого массива методом splice() ?

Первым параметром мы указываем стартовый индекс, с которого начнётся добавление нового массива. В нашем случае добавлять будем в начало т. е. добавляемый массив станет первым элементом оригинального массива — это индекс 0 . Остальные элементы сдвинутся вправо. Длина оригинального массива увеличится.

Вторым параметром мы указываем сколько элементов оригинального массива мы хотим заменить во время вставки. В нашем случае мы не хотим заменять ни одного элемента оригинального массива, поэтому указываем 0 .

Третьим параметром мы передаём сам новый массив, который станет первым элементом оригинального массива — это [55, 55] .

var massiv = [1, 2, 3, 4] massiv.splice(0, 0, [55, 55])

Теперь наш массив имеет вид:

[[55, 55], 1, 2, 3, 4]

Добавили массив в начало другого массива - JavaScript

Мы успешно добавили массив в начало другого массива и сохранили все «сдвинутые» элементы.

Как добавить массив в середину другого массива методом splice() ?

Понятие «середина» означает то, что мы пытаемся вставить элемент не последним и не первым. Вставленный массив будет где-то между — по середине.

Например, вставляемый массив [55, 55] мы сделаем третьим элементом оригинального массива.

var massiv = [1, 2, 3, 4] massiv.splice(2, 0, [55, 55])

Теперь наш массив имеет вид:

[1, 2, [55, 55], 3, 4]

Добавили массив в середину другого массива - JavaScript

Как добавить массив в конец другого массива методом splice() ?

Метод splice() работает таким образом, что если мы укажем в качестве стартового индекса « -1 «, то применится правило, которое закинет наш массив не в конец, а в пред-конец. То есть наш вставляемый массив станет предпоследним элементом. И это не совсем то, что нам нужно.

Читайте также:  Travel templates free html

По этой причине нам нужно вызывать два метода splice() :

  • Один из splice() будет третим параметром другого splice()
  • Другой из splice() будет методом вызова на оригинальном массиве

Конструкция кода будет выглядеть так:

massiv.splice(-1, 0, . massiv.splice(-1, 1, [55, 55]))

Теперь наш массив имеет вид:

[1, 2, 3, 4, [55, 55]]

Добавили массив в конец другого массива - JavaScript

Как это работает?

Первая трансформация оригинального массива:

Эта конструкция изменяет оригинальный массив на [1, 2, 3, [55, 55] ] и возвращает нам удалённые элементы — другой массив [4].

Вторая трансформация оригинального масива:

Теперь, если мы вызовем метод splice() на массиве [1, 2, 3, [55, 55] ] со стартовой позицией также «-1», и не удалим элементы (создадим сдвиг), и распакуем элементы массива [4] при помощи троеточия (spread), то получим нужный результат

[1, 2, 3, 4, [55, 55]]

Источник

Javascript Add Array To Array — Extend Them

In this article, You will learn how to extend a JavaScript array by adding another array to it using various different methods.

Normally adding another array to the existing array makes the entire array an element of the original array.

If you want to make every element of another array an element of the existing array then you need to extend the array.

javascript add array to array example1

Let’s see how to extend a javascript array as shown in the above image.

Javascript add array to array

  • Using concat() Method
  • Using push() Method
  • Using spread operator
  • Using for loop
  • Using splice() Method
  • 1. Extend Array Using concat Method

    The array concat() method merges 2 or more than 2 array or array-like objects, or any values into a single array.

    The method is called on an array and returns a new array consisting of the elements of the original array followed by elements passed in the methods.

    array.concat(value1, value2, . valueN)

    Here value1 to valueN are the values you want to add to the original array. It can be an array or any value like string, number, boolean, etc.

    Читайте также:  Ссылки

    Let’s see how to extend an array using concat method.

    var arr1 = [1, 2, 3]; var arr2 = [4, 5, 6]; // javascript add array to array // extend arr2 to arr1 arr1 = arr1.concat(arr2); console.log(arr1); // [1, 2, 3, 4, 5, 6]

    You can also pass a direct array in the concat method.

    var arr1 = [1, 2, 3]; // javascript add array to array // extend [4, 5, 6] to arr1 arr1 = arr1.concat([4, 5, 6]); console.log(arr1); // [1, 2, 3, 4, 5, 6]

    concat() method is slow if a is large but faster than loop. If original array is small and have to add too many elements than it is significantly faster than using loop.

    2. Extend Array Using push Method

    The push() method is a general array method to add a new element to the end of an array. But if you directly pass an array in the push method then the entire array will be added as a single element in the array.

    var arr1 = [1, 2, 3]; var arr2 = [4, 5, 6]; // push arr2 to arr1 arr1.push(arr2); console.log(arr1); // [1, 2, 3, [4, 5, 6]]

    You can see that the push method adds the array as single element in the array. But we want each element of the array to be added as an element of the original array.

    To do this we spread the array in the push method using spread operator.

    var arr1 = [1, 2, 3]; var arr2 = [4, 5, 6]; // extend arr2 to arr1 arr1.push(. arr2); console.log(arr1); // [1, 2, 3, 4, 5, 6]

    push method is very fast if original array is big and few elements are added.

    3. Extend Array Using spread operator

    The spread operator is javascript’s new feature to expand an array into a list of arguments.

    Читайте также:  Java running jar main class

    You can use this operator to spread 2 or more than 2 arrays and convert them into a single array.

    To use the spread operator to extend array to array we spread both arrays in a square bracket. Here is an example:

    var arr1 = [1, 2, 3]; var arr2 = [4, 5, 6]; // using spread operator // to extend/add array to array arr1 = [. arr1, . arr2]; console.log(arr1); // [1, 2, 3, 4, 5, 6]

    4. Extend Array Using for loop

    for loop can be used to extend an array.

    Loop through the array and push each element one by one at the end of original array.

    var arr1 = [1, 2, 3]; var arr2 = [4, 5, 6]; // using for loop // to extend/add array to array for (var i = 0; i < arr2.length; i++) < arr1.push(arr2[i]); >console.log(arr1); // [1, 2, 3, 4, 5, 6]

    5. Extend Array Using splice

    The splice method is a general array method that can be used to add and remove elements from an array.

    arr.splice(index, howMany, item1, . itemX)

    Here, the index is the position where the new elements will be added. howMany is the number of elements to be removed. item1 to itemX are the new elements to be added.

    For array, you can use the spread operator to convert an array into a list of arguments.

    var arr1 = [1, 2, 3]; var arr2 = [4, 5, 6]; // using splice method with spread operator // to extend/add array to array arr1.splice(arr1.length, 0, . arr2); console.log(arr1); // [1, 2, 3, 4, 5, 6]

    In the above example, we want to add a new element after the last element of the array. So we use arr1.length to get the last index of the array.

    Conclusion

    We have learned how javascript add array to array using 5 different method.

    Among all push() method is most commonly used to add elements. Spread the element using the spread operator to extend the elements in the array.

    Источник

    Оцените статью