Javascript add element to array begin

Push an Item to the Beginning of an Array in JavaScript

How do you push an item to the beginning of an array using JavaScript?

In this article, we’ll show you four different ways to do this using plain JavaScript:

  1. The unshift() Method
  2. The concat() Method
  3. The ES6 Spread Operator . Method
  4. The splice() Method

We’ll cover each of those methods in more detail below and provide you with code samples as well.

Table Of Contents

1. Unshift() Method

The unshift() method adds one or more items to the beginning of an array and returns the new length of the modified array.

Here’s what it looks like in a code example:

let originalArray = ["Taco", "Hamburger", "Hot Dog", "Chicken"] originalArray.unshift("Veal") console.log(originalArray) // Result: ["Veal", "Taco", "Hamburger", "Hot Dog", "Chicken"] 

The unshift() method takes one or multiple parameters of the element you want to append to the front of the array.

If you add multiple items to the function as parameters, they will be added as chunk at the beginning in the same exact order you passed them as arguments.

It’s also important to note that this method will return the length of the newly created array (not the new array itself). This will differ with some of the other methods we cover in this article and will be either good or bad depending on your use case.

Check out the MDN Web Documentation for more specific information on the unshift() method.

In the next section, we’ll cover the concat() method.

2. Concat() Method

The concat() method is used to combine two or more arrays. It doesn’t change anything about the arrays given to the method but simply returns the newly created array.

Here’s what the code looks like when using the concat() method to append an item to the front of an array:

const originalArray = ["Taco", "Hamburger", "Hot Dog", "Chicken"] const newArray = ["Veal"].concat(originalArray) console.log(newArray) // Result: ["Veal", "Taco", "Hamburger", "Hot Dog", "Chicken"] 

In contrast to the array length value returned by the unshift() method, concat() will return a shallow copy of the newly created array. Therefore, this method is good for you to use when the original array needs to remain unchanged for whatever reason.

Читайте также:  Графический web редактор html

Check out the MDN Web Documentation for more specific information on the concat() method.

The next method we’ll cover is the ES6 Spread Operator.

3. ES6 Spread Operator

The spread syntax was a feature added to the ES6 version of JavaScript that allows you to iterate over an array and expand its values where zero or more arguments or elements are expected.

In layman’s terms, it allows you to manipulate strings, arrays, and objects in a syntax that is more succinct and easier to use compared to other methods. And it can be used specifically to push an item to the beginning of an array.

Here’s what the code looks like:

let originalArray = ["Taco", "Hamburger", "Hot Dog", "Chicken"] originalArray = ["Veal", . originalArray] console.log(originalArray) // Result: ["Veal", "Taco", "Hamburger", "Hot Dog", "Chicken"] 

Using the spread operator in this way simply creates a new version of the array and where «Veal» is placed in the first position.

This method isn’t supported in all browsers. Specifically, none of the Internet Explorer browser versions support the ES6 spread operator.

Check out the MDN Web Documentation for more specific information on the ES6 Spread Operator.

In the next section, we’ll cover the last splice() method.

4. Splice() Method

The splice() method alters the contents of an array by the mode of removing or replacing existing elements and/or adding new ones in their place.

Here’s what the method looks like in practice:

let originalArray = ["Taco", "Hamburger", "Hot Dog", "Chicken"] originalArray.splice(0, 0, "Veal") console.log(originalArray) // Result: ["Veal", "Taco", "Hamburger", "Hot Dog", "Chicken"] 

The splice() method takes three parameters in this order:

  1. The index at which you want to begin altering the array.
  2. An integer specifying how many elements in the array to remove from the start.
  3. The elements you want to add to the array (beginning from the start point).

In our code example, we gave both the first and second parameter a 0 value. By giving those items a value of 0 , we’re telling the splice() method to insert our element at the beginning of the originalArray we provided.

Check out the MDN Web Documentation for more specific information on the splice() method.

That was the last method we’ll cover in this article.

Источник

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.

Читайте также:  Javascript proxy и reflect

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.

Источник

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.

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

Источник

JavaScript Array unshift()

The unshift() method adds new elements to the beginning of an array.

The unshift() method overwrites the original array.

See Also:

Syntax

Parameters

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

Return Value

Browser Support

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

Источник

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