Add array items to array javascript

JavaScript Array push()

The push() method adds new items to the end of an array.

The push() method changes the length of the array.

The push() method returns the new length.

See Also:

Syntax

Parameters

Parameters Description
item1
item2
..
itemX
The item(s) to add to the array.
Minimum one item is required.

Return Value

More Examples

push() returns the new length:

Browser Support

push is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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.

Источник

Add array items to array javascript

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']

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']

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']

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); // 👉️ []

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.

Источник

Читайте также:  Python pip install index url
Оцените статью