Javascript array insert all

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() .

Читайте также:  Javascript document all true

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.

Источник

6 Ways to Insert Elements to an Array in JavaScript

In this article, I will show you 6 different ways of adding elements to an array in JavaScript. I will also include ES6 methods.

  • #1 push – Add an element to the end of the array
  • #2 unshift – Insert an element at the beginning of the array
  • #3 spread operator – Adding elements to an array using the new ES6 spread operator
  • #4 concat – This can be used to append an array to another array
  • #5 Using the arrays length property to append an element
  • #6 splice – inserts an element anywhere in an array

As you can see, there are multiple ways to add elements to an array in JavaScript. In this article, I will go into detail about each one with examples.

#1 The push() method

The push() method “pushes” elements to the end of the array.

Add a single element:

let array = ['1', '2', '3']; array.push('4'); console.log(array); // returns ['1', '2', '3', '4']

You can also add multiple elements by using multiple parameters in the push() method:

let array = ['1', '2', '3']; array.push('4', '5', '6'); console.log(array); // returns ['1', '2', '3', '4', '5', '6']

You can append an array to an existing array by using push.apply()

let a = ['1', '2', '3']; let b = ['4', '5', '6']; a.push.apply(a, b); console.log(a); // returns ['1', '2', '3', '4', '5', '6']

#2 The unshift() method

The unshift() method inserts elements to the beginning of the array.

Inserting a single element:

let array = ['1', '2', '3']; array.unshift('0'); console.log(array); // returns ['0', '1', '2', '3']

Inserting multiple elements:

let array = ['1', '2', '3']; array.unshift('-1', '0'); console.log(array); // returns ['-1', '0', '1', '2', '3']

#3 The concat method

The concat() method doesn’t actually append elements to an existing array but instead, creates a brand new array.

This means that the original array won’t change.

Why is this important? Here is an example:

let originalArray = ['1', '2', '3']; let appendingArray = ['4', '5', '6']; let newArray = originalArray.concat(appendingArray); console.log(newArray); // returns ['1', '2', '3', '4', '5', '6'] console.log(originalArray); // returns ['1', '2', '3']

As you can see, the original array stays the same.

You are not mutating the original array which means you are not changing it.

This can be useful if you need to use the data from the original array to other stuff.

You can also take an empty array and concat multiple arrays. We do that by adding multiple parameters in the concat method.

let a = ['1', '2', '3']; let b = ['4', '5', '6']; let result = [].concat(a, b); console.log(result); // returns ['1', '2', '3', '4', '5', '6']

#4 The spread operator (ES6)

With the ES6 syntax, we can use the spread operator. It is similar to concat where we create a new array instead of adding to the existing one.

This is a flexible way of working with arrays and very popular with the “new” JavaScript.

Let’s get started with an example:

let a = ['1', '2', '3']; let newArray = ['0', . a, '4']; console.log(newArray); // returns ['0', '2', '3', '4']

As you can see, we are placing the entire array in the middle of the new array declaration. We do this by writing three dots before the variable name. This is the ES6 syntax.

As you can imagine, we can place the array anywhere we want.

We can also use the spread operator together with the push method:

let a = ['1', '2', '3']; let b = ['4', '5'] a.push(. b); console.log(a); // returns ['0', '1', '2', '3', '4', '5']

#5 Using the array length property

You can also append an array by using the arrays length property as an index.

let a = ['1', '2', '3']; a[a.length] = '4'; console.log(a); // returns ['1', '2', '3', '4']

The first element of an array has index number 0.

So in the example above, we have three elements. The elements have index 0, 1 and 2. a.length will return 3 since we have three elements.

Therefore it will append at the end of the array.

You can not insert elements in any other place using this method. If I would set a[1] = ‘5’ , it would just change the existing element.

#6 The splice method

You can insert elements anywhere in the array using the splice method().

The splice method is used in the following way: array.splice(index, how many to delete, element 1, element 2) .

The first parameter you define where in the array you want to insert data. The second parameter you define how many elements you want to delete. We only want to insert elements, so we put 0 here. The last parameters are the elements you want to insert.

let a = ['1', '2', '3']; a.splice(2, 0, '4', '5'); console.log(a); // returns ['0', '2', '4', '5', '3']

I am a full-stack web developer with over 13 years of experience. I love learning new things and are passionate about JavaScript development both on the front-end and back-end.

Recent Posts

In this article, we will look at sorting an array alphabetically in JavaScript. We will cover both arrays with strings and arrays with objects. Sorting an Array with Strings When sorting an.

In this tutorial, I will show you how to programmatically set the focus to an input element using React.js and hooks. We will use two hooks, useRef and useEffect. Set up the Project All you.

About Us

We are a team of passionate web developers with decades of experience between us.

This site will focus mostly on web development. We love writing and we want to share our knowledge with you.

Hope you’ll enjoy and have fun coding!

Источник

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