Javascript adding element to array

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.

Источник

Push into an Array in JavaScript – How to Insert an Element into an Array in JS

Joel Olawanle

Joel Olawanle

Push into an Array in JavaScript – How to Insert an Element into an Array in JS

The array datatype is one of the most commonly used datatypes when you’re working with an ordered list of values.

Each value is referred to as an element with a unique id . It stores elements of various datatypes that you can access through a single variable.

In practice, an array could hold a list of users, and we might need to add an element(s) to the array after the last element, before the first element, or at any specified point in our array.

This article will show you how to insert an element into an array using JavaScript. In case you’re in a hurry, here are the methods we’ll be discussing in depth in this article:

// Add to the start of an array Array.unshift(element); // Add to the end of an array Array.push(element); // Add to a specified location Array.splice(start_position, 0, new_element. ); // Add with concat method without mutating original array let newArray = [].concat(Array, element); 
  • When you want to add an element to the end of your array, use push() .
  • If you need to add an element to the beginning of your array, use unshift() .
  • If you want to add an element to a particular location of your array, use splice() .
  • And finally, when you want to maintain your original array, you can use the concat() method.

How to push to the start of an array with the unshift() method

In JavaScript, you use the unshift() method to add one or more elements to the beginning of an array and it returns the array’s length after the new elements have been added.

If we have an array of countries and want to add a country before «Nigeria,» which is currently at the first index 0 , we can do so with the unshift() method, as shown below:

const countries = ["Nigeria", "Ghana", "Rwanda"]; countries.unshift("Kenya"); console.log(countries); // ["Kenya","Nigeria","Ghana","Rwanda"] 

As we said, we can also add more than one element using the unshift() method:

const countries = ["Nigeria", "Ghana", "Rwanda"]; countries.unshift("South Africa", "Mali", "Kenya"); console.log(countries); // ["South Africa","Mali","Kenya","Nigeria","Ghana","Rwanda"] 

In our explanation of the unshift() method, we also stated that it returns the length of the new array, which is true:

const countries = ["Nigeria", "Ghana", "Rwanda"]; let countriesLength = countries.unshift("South Africa", "Mali", "Kenya"); console.log(countriesLength); // 6 

How to push to the end of an array with the push() method

The push() method is similar to the unshift() method as it adds an element to the end of an array rather than the beginning. It returns the length of the new array and, like the unshift() method, can be used to add more than one element.

Let’s try the same example again, but this time add them to the end of the array using the push() method:

const countries = ["Nigeria", "Ghana", "Rwanda"]; countries.push("Kenya"); console.log(countries); // ["Nigeria","Ghana","Rwanda","Kenya"] countries.push("South Africa", "Mali"); console.log(countries); // ["Nigeria","Ghana","Rwanda","Kenya","South Africa","Mali"] 

And like we said, we can use it to get the length of the new array:

const countries = ["Nigeria", "Ghana", "Rwanda"]; let countriesLength = countries.push("Kenya"); console.log(countriesLength); // 4 

How to push to a specified location in an array with the splice() method

So far, we’ve only seen how to add an element to the beginning or end of an array. But you might wonder how to add an element to a specific location within an array. Well, you can do it with the splice() method.

The splice() method is a general-purpose method for changing the contents of an array by removing, replacing, or adding elements in specified positions of the array. This section will cover how to use this method to add an element to a specific location.

For example, consider the following array of countries, which contains three elements (countries) arranged alphabetically:

const countries = ["Ghana", "Nigeria", "Rwanda"]; 

Suppose we want to add «Kenya,» which, according to alphabetical order, should be placed in the second position, index 1 (after Ghana and before Nigeria). In that case, we will use the splice() method with the following syntax:

Array.splice(start_position, 0, new_element. ); 
  • The start_position specifies the index of where we want the new elements to be inserted in the array. If there are multiple elements, it specifies where the elements inserted will start.
  • If we want to add to the array, we set the second argument to zero ( 0 ), instructing the splice() method not to delete any array elements.
  • The following parameter(s) or element(s) may be more than one, as these are the elements we want to add to the array at the specified position.

For example, let’s place «Kenya» after «Ghana» in our countries array:

const countries = ["Ghana", "Nigeria", "Rwanda"]; countries.splice(1, 0, 'Kenya'); console.log(countries); // ["Ghana","Kenya","Nigeria","Rwanda"] 

s_8F843EE332F48B356BFA84EB69212DF653EB2859C5739E7748DB9362133DCFB7_1658069550677_illustration

Just as we did for other methods, we can also add more than one element:

const countries = ["Ghana", "Nigeria", "Rwanda"]; countries.splice(1, 0, 'Kenya', 'Mali'); console.log(countries); // ["Ghana","Kenya","Mali","Nigeria","Rwanda"] 

Note that the previous methods returned the length of the new array, but the splice method changes the original array. It does not remove any elements, so it returns an empty array.

How to push elements into an array with the concat() method

We can use the concat() method to add elements to an array without mutating or altering the original array. Instead, creating a new one is a better method if we don’t want the original array to be affected.

We can use this method to add elements to both the beginning and end of the array based on where we place the elements:

const countries = ["Ghana", "Nigeria", "Rwanda"]; let newCountries = [].concat("Mali", countries, "Kenya"); console.log(newCountries); // ["Mali","Ghana","Nigeria","Rwanda","Kenya"] 

The concat() method also allows us to join together two (or more) arrays into a single new array:

const africanCountries = ["Ghana", "Nigeria", "Rwanda"]; const europeanCountries = ["Germany", "France", "spain"]; let countries = [].concat(africanCountries, europeanCountries); console.log(countries); // ["Ghana","Nigeria","Rwanda","Germany","France","spain"] 

Wrapping up

In this article, we learned various ways to push elements into an array to the start, end, or any position using the splice() method.

We also learned that the concat() method allows us to push elements without altering the original array.

Use any method that fits your needs.

Embark on a journey of learning! Browse 200+ expert articles on web development written by me. Check out my blog for more captivating content from me.

Источник

Читайте также:  Основы PHP и MySQL
Оцените статью