Javascript appending array to array

Array.prototype.push()

The push() method adds the specified elements to the end of an array and returns the new length of the array.

Try it

Syntax

push() push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) 

Parameters

The element(s) to add to the end of the array.

Return value

The new length property of the object upon which the method was called.

Description

The push() method appends values to an array.

Array.prototype.unshift() has similar behavior to push() , but applied to the start of an array.

The push() method is a mutating method. It changes the length and the content of this . In case you want the value of this to be the same, but return a new array with elements appended to the end, you can use arr.concat([element0, element1, /* . ,*/ elementN]) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of concat() .

The push() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

Examples

Adding elements to an array

The following code creates the sports array containing two elements, then appends two elements to it. The total variable contains the new length of the array.

const sports = ["soccer", "baseball"]; const total = sports.push("football", "swimming"); console.log(sports); // ['soccer', 'baseball', 'football', 'swimming'] console.log(total); // 4 

Merging two arrays

This example uses spread syntax to push all elements from a second array into the first one.

const vegetables = ["parsnip", "potato"]; const moreVegs = ["celery", "beetroot"]; // Merge the second array into the first one vegetables.push(. moreVegs); console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot'] 

Merging two arrays can also be done with the concat() method.

Calling push() on non-array objects

The push() method reads the length property of this . It then sets each index of this starting at length with the arguments passed to push() . Finally, it sets the length to the previous length plus the number of pushed elements.

const arrayLike =  length: 3, unrelated: "foo", 2: 4, >; Array.prototype.push.call(arrayLike, 1, 2); console.log(arrayLike); // const plainObj = >; // There's no length property, so the length is 0 Array.prototype.push.call(plainObj, 1, 2); console.log(plainObj); // 

Using an object in an array-like fashion

As mentioned above, push is intentionally generic, and we can use that to our advantage. Array.prototype.push can work on an object just fine, as this example shows.

Note that we don’t create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way JavaScript allows us to establish the execution context in any way we want.

const obj =  length: 0, addElem(elem)  // obj.length is automatically incremented // every time an element is added. [].push.call(this, elem); >, >; // Let's add some empty objects just to illustrate. obj.addElem(>); obj.addElem(>); console.log(obj.length); // 2 

Note that although obj is not an array, the method push successfully incremented obj ‘s length property just like if we were dealing with an actual array.

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 Jul 19, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Javascript appending array to array

Last updated: Dec 26, 2022
Reading time · 5 min

banner

# Table of Contents

# Append one Array to another Array in JavaScript

To append one array to another:

  1. Use the spread syntax (. ) to unpack the values of the two arrays into a third array.
  2. The spread syntax will return a new array by appending the second array to the first array.
Copied!
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; const arr3 = [. arr1, . arr2]; console.log(arr3); // 👉️ ['a', 'b', 'c', 'd']

append one array to another array

We used the spread syntax (. ) to unpack the values of two arrays into a third array.

The easiest way to think about it is:

  1. We grab all the values of arr1 and add them to arr3 .
  2. We grab all the values of arr2 and add them to arr3 .

The order in which we unpacked the arrays is preserved and all of the elements of arr1 come before the elements of arr2 .

The spread syntax (. ) is commonly used when you need to add new elements to an array without changing the contents of the original array.

Copied!
const arr1 = ['a', 'b']; const arr2 = [. arr1, 'c', 'd']; console.log(arr2); // 👉️ ['a', 'b', 'c', 'd']

Using the spread syntax to append one another to another is very performant.

# Append one Array to another array using Array.concat()

Alternatively, you can use the Array.concat() method.

The Array.concat() method will merge the two arrays into a third array and will return the result.

Copied!
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; const arr3 = arr1.concat(arr2); console.log(arr3); // 👉️ ['a', 'b', 'c', 'd']

append one array to another array using array concat

We used the Array.concat() method to merge two arrays into a third.

The method doesn’t change the contents of the original arrays, instead it returns a new array.

The method takes the array(s) you want to concatenate into the new array as parameters.

Here’s an example of calling the concat() method with multiple arrays.

Copied!
const arr1 = ['a', 'b']; const arr2 = arr1.concat(['c'], ['d'], ['e']); console.log(arr2); // 👉️ ['a', 'b', 'c', 'd', 'e']

All of the arrays we passed to the Array.concat() method, including arr1 got merged into a new array.

You can even pass non-array values to the concat() method.

Copied!
const arr1 = ['a', 'b']; const arr2 = arr1.concat('c', 'd', ['e']); console.log(arr2); // 👉️ ['a', 'b', 'c', 'd', 'e']

We passed two strings and an array to the concat() method and they all got merged into the new array.

# Append one Array to another Array using push()

An alternative approach is to use the push() method.

The Array.push() method is used to add one or more elements to the end of an array.

Copied!
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; arr1.push(. arr2); console.log(arr1); // 👉️ ['a', 'b', 'c', 'd', 'e']

append one array to another array using push

We used the spread operator (. ) to unpack the values of arr2 when calling the Array.push method.

The push() method takes one or more values as parameters. The parameters get pushed to the end of the array.

The method mutates the array in place.

You can also use a simple while loop.

# Append one Array to another Array using a while loop

This is a three-step process:

  1. Use a while loop to iterate over the second array.
  2. On each iteration, use the Array.shift() method to remove the first element from the array.
  3. Use the Array.push() method to push the removed element into the other array.
Copied!
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; while (arr2.length) arr1.push(arr2.shift()); > console.log(arr1); // 👉️ [ 'a', 'b', 'c', 'd' ] console.log(arr2); // 👉️ []

append one array to another array using while loop

We used a while loop to iterate for as long as the length of arr2 is greater than 0 .

On each iteration, we use the Array.shift() method to remove and return the first element from the second array.

Copied!
const arr2 = ['c', 'd']; console.log(arr2.shift()); // 👉️ c

We directly passed the output of the Array.shift() method to the Array.push() method to push the element into the first array.

The while loop appends the contents of the second array to the first array, in place.

You can also use the Array.forEach() method.

# Append one Array to another Array using Array.forEach()

This is a two-step process:

  1. Use the Array.forEach() method to iterate over the second array.
  2. Use the Array.push() method to push each element into the first array.
Copied!
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; for (const element of arr2) arr1.push(element); > console.log(arr1); // 👉️ [ 'a', 'b', 'c', 'd' ]

The function we passed to the Array.forEach method gets called with each element in the array.

On each iteration, we use the Array.push() method to push the element into the first array.

This approach mutates the contents of the first array only, whereas the while loop approach changed both arrays in place.

# Append one Array to another Array using for. of

You can also use a for. of loop to append one array to another array.

Copied!
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; for (const element of arr2) arr1.push(element); > console.log(arr1); // 👉️ [ 'a', 'b', 'c', 'd' ]

The for. of statement is used to loop over iterable objects like arrays, strings, Map , Set and NodeList objects and generators .

On each iteration, we use the Array.push() method to add the element of the second array to the first array.

# Append one Array to another Array using a for loop

You can also use a basic for loop to append one array to another array.

Copied!
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; for (let index = 0; index arr2.length; index++) arr1.push(arr2[index]); > console.log(arr1); // 👉️ [ 'a', 'b', 'c', 'd' ]

The syntax for a basic for loop is quite verbose and we have to make use of the index to access the array.

Which approach you pick is a matter of personal preference. I’d use the spread syntax because it’s quite performant and easy to read.

Copied!
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; const arr3 = [. arr1, . arr2]; console.log(arr3); // 👉️ ['a', 'b', 'c', 'd']

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

JavaScript Append Array to Another

JavaScript Append Array to Another

  1. Append an Array to Another Using the push() Function in JavaScript
  2. Append an Array to Another Using the concat() Function in JavaScript

This tutorial will discuss how to append an array with another array using the push() and concat() function in JavaScript.

Append an Array to Another Using the push() Function in JavaScript

To append an array with another, we can use the push() function in JavaScript. The push() function adds an array of items to another array. For example, let’s add all of its array items into another array using the push.apply() function. See the code below.

var myArray = ['a', 'b', 'c']; var myArray2 = ['f', 'e'] myArray.push.apply(myArray, myArray2); console.log(myArray) 

As you can see in the output, the two items present in the myArray2 have been added to the myArray .

Append an Array to Another Using the concat() Function in JavaScript

You can also concatenate two arrays to make another array using the concat() function. For example, let’s concatenating one array with another array using the concat() function. See the code below.

var myArray = ['a', 'b', 'c']; var myArray2 = ['d', 'e'] var myArray = myArray.concat(myArray2); console.log(myArray) 

You can change the order of the items present in the myArray by changing the order of concatenation. Note the above two functions will fail if the array is too long. In this case, you can create your own function to append the two arrays. For example, let’s create a function with the name AppendArray using a for loop to append an array with another array. See the code below.

function AppendArray(arr1, arr2)  l1 = arr1.length;  l2 = arr2.length;  for (i=0 ; il2 ;i++)  arr1[l1+i] = arr2[i];  >  return arr1; > var myArray = ['a', 'b', 'c']; var myArray2 = ['d', 'e'] var myArray = AppendArray(myArray, myArray2); console.log(myArray) 

In the above code, we get the elements of arr2 using their index and adding them into arr2 at the end. The loop will continue until all the elements of arr2 have been added to arr1 . The length function is used to get the length of an array.

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

Related Article — JavaScript Array

Источник

Читайте также:  Image info in php
Оцените статью