Javascript add array element at beginning

Add to the Front of an Array in JavaScript

You can use the unshift() function to add elements to the beginning of an array. unshift() modifies the array in place, and returns new length of the array.

let array = [1, 2, 3]; array.unshift(0); // 4 array; // [0, 1, 2, 3] array = ['b', 'c']; array.unshift('a'); // 3 array; // ['a', 'b', 'c']

Immutable Approaches

If you need to create a shallow copy of the array and append a new element at the beginning, you have a couple of options. You can use the concat() method to add elements the beginning to the array as follows:

const array1 = [4, 5, 6]; const array2 = [1, 2, 3]; array2.concat(array1); // returns [1, 2, 3, 4, 5, 6] [0].concat(array2); // returns [0, 1, 2, 3]

The key point is that concat() doesn’t modify the original array. It will instead return a copy of the array with one or more new elements at the beginning.

Читайте также:  Активировать майнкрафт java edition

Spread Operator

You can also use the spread operator to create a new array with a new element at the beginning as shown below. This approach is common in React codebases.

const array1 = [1, 2, 3]; [0, . array1]; // returns [0, 1, 2, 3]

More Fundamentals Tutorials

Источник

Array.prototype.unshift()

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

Try it

Syntax

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

Parameters

The elements to add to the front of the arr .

Return value

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

Description

The unshift() method inserts the given values to the beginning of an array-like object.

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

Please note that, if multiple elements are passed as parameters, they’re inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling unshift() with n arguments once, or calling it n times with 1 argument (with a loop, for example), don’t yield the same results.

let arr = [4, 5, 6]; arr.unshift(1, 2, 3); console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6]; // resetting the array arr.unshift(1); arr.unshift(2); arr.unshift(3); console.log(arr); // [3, 2, 1, 4, 5, 6] 

The unshift() 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

Using unshift()

const arr = [1, 2]; arr.unshift(0); // result of the call is 3, which is the new array length // arr is [0, 1, 2] arr.unshift(-2, -1); // the new array length is 5 // arr is [-2, -1, 0, 1, 2] arr.unshift([-4, -3]); // the new array length is 6 // arr is [[-4, -3], -2, -1, 0, 1, 2] arr.unshift([-7, -6], [-5]); // the new array length is 8 // arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ] 

Calling unshift() on non-array objects

The unshift() method reads the length property of this . It shifts all indices in the range 0 to length — 1 right by the number of arguments (incrementing their values by this number). Then, it sets each index starting at 0 with the arguments passed to unshift() . Finally, it sets the length to the previous length plus the number of prepended elements.

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

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 Jun 27, 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.

Источник

How to Add Element at Beginning of an Array in JavaScript

In this tutorial, we’ll learn different ways of adding new elements at the beginning of an Array in JavaScript.

Using Array.unshift()

The easiest way to add elements at the beginning of an array is to use unshift() method.

var fruits = ["Apple", "Banana", "Mango"];  fruits.unshift("Orange"); console.log(fruits); // Prints ["Orange", "Apple", "Banana", "Mango"]  fruits.unshift("Guava", "Papaya"); console.log(fruits); // Prints ["Guava", "Papaya", "Orange", "Apple", "Banana", "Mango"] 

It adds the elements of your original array. Sometime you wish not to alter the original array, and assign it to a new variable instead.

In Javascript, you can do this in multiple ways in a single statement.

Using Spread Operator (…)

We can use spread operator . to make a copy of an array. It’s short syntax is very handy.

var fruits = ["Apple", "Banana", "Mango"];  var moreFruits = ["Orange", . fruits]; console.log(moreFruits); // Prints ["Orange", "Apple", "Banana", "Mango"]  var someoMoreFruits = ["Guava", "Papaya", . moreFruits]; console.log(someoMoreFruits); // Prints ["Guava", "Papaya", "Orange", "Apple", "Banana", "Mango"]  console.log(fruits); // Prints ["Apple", "Banana", "Mango"] 

New elements are added at the beginning followed by copy of the original Array (using . ) and assigned to a new variable.

We see that our original array remains the same.

Using Array.concat()

We can also user concat() method to join two (or more) arrays at the beginning.

var fruits = ["Apple", "Banana", "Mango"]; var moreFruits = ["Orange"]; var someoMoreFruits = ["Guava", "Papaya"];  var allFruits = someoMoreFruits.concat(moreFruits, fruits); console.log(allFruits); // Prints ["Guava", "Papaya", "Orange", "Apple", "Banana", "Mango"] 

See Also

Ashish Lahoti avatar

Ashish Lahoti is a Software Engineer with 12+ years of experience in designing and developing distributed and scalable enterprise applications using modern practices. He is a technology enthusiast and has a passion for coding & blogging.

Источник

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