Javascript array push first

JavaScript Add Element to Beginning & Ending of Array

Add element to beginning and end of array JavaScript; In this tutorial, you will learn how to add element at the beginning and at the end of an array in javascript.

javascript has two built-in array methods, which is unshift() and push(), which are used to add elements or items at first or beginning and last or ending of an array in javascript.

Читайте также:  Как сделать модуль html

This tutorial has the purpose to explain how to add an element at the beginning and ending of an array in javascript using these unshift and push js methods. Also, we will explain definition, syntax, parameters, with examples.

JavaScript add Element beginning and ending of array

In this tutorial, You will learn two methods with its definition, syntax, parameters with examples to add element or item first or beginning and last or ending of an array javascript.

1. JavaScript Add Element to Beginning of array JavaScript

2. JavaScript Add Element to Ending of array JavaScript

1. JavaScript Add Element to Beginning of array JavaScript

You can use the javascript unshift() method to add elements or items first or beginning array in javascript.

unshift() method javascript

Definition:- The javaScript unshift() method adds new items to the first or beginning of an array. and it will return the new length of array.

Syntax of unshift() method is

array.unshift(element1, element2, . elementX)

Parameter with description

Example – add element start or beginning of an array javascript

Consider, we have an array that’s the name arrNum, and it contains four elements inside it, see below:

var arrNum = [ "one", "two", "three", "four" ];

If you want to add element start or beginning of an arrNum array. So you can use the unshift() method of javaScript like below:

var arrNum = [ "one", "two", "three", "four" ]; arrNum.unshift("zero"); console.log( arrNum );

The result of the above example is:

2. JavaScript Add Element to Ending of array JavaScript

You can use the javascript push() method to add the elements or items from the last or end of an array.

push() method javascript

Definition: – The javaScript push() method is used to add a new element to the last or end of an array.

Syntax of push() method is

array.push( element1, element2, . elementX )

Parameter with description

Example – javascript add the element to last or end of an array

Consider, we have an array that’s the name arrNum, and it contains four elements inside it, see below:

var arrNum = [ "one", "two", "three", "four" ];

If you want to add the single item into the arryNum array. So you can use the push() method of javaScript like below:

var arrNum = [ "one", "two", "three", "four" ]; arrNum.push("five"); console.log( arrNum );

The result of the above example is:

If you want to see more example of javascript push() method, you can click and see here

Источник

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.

Источник

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