Javascript array insert first

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.

Читайте также:  Php get all method in class

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!

Источник

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.

Источник

How to Insert into a JavaScript Array at a Specific Index – JS Push

Joel Olawanle

Joel Olawanle

How to Insert into a JavaScript Array at a Specific Index – JS Push

JavaScript arrays are an important part of the language. They allow you to store and manipulate collections of data.

Sometimes, you may need to insert a new element into an array at a specific index. To accomplish this task, you can use the push() method or the splice() method.

In this article, you will learn how to use both techniques in detail.

How JavaScript Arrays Work

Before we dive into the insertion methods, let’s briefly review arrays in JavaScript.

An array is a collection of data values of any data type. You can create arrays using either the array constructor or the literal notation.

Here’s an example of an array created using the array constructor:

const arrayConstructor = new Array(1, 2, 3); console.log(arrayConstructor); // Output: [1, 2, 3] 

And here’s an example of an array created using literal notation:

const literalArray = [1, 2, 3]; console.log(literalArray); // Output: [1, 2, 3] 

In both cases, you have an array with three elements: 1 , 2 , and 3 .

How to Insert into a JavaScript Array at a Specific Index With the push() Method

The push() method in JavaScript arrays is used to add one or more elements to the end of an array.

Let’s look at the syntax of the push() method:

array.push(element1, element2, . elementN); 

Here, array is the array that you want to add elements to, and element1 , element2 , and so on, are the elements you want to add to the end of the array.

For example, let’s say you have an array of fruit, and you want to add an element to the end of it:

const fruits = ['apple', 'banana', 'cherry']; fruits.push('date'); console.log(fruits); // Output: ['apple', 'banana', 'cherry', 'date'] 

In this code, ‘date’ is added to the end of the fruits array using the push() method.

There may be times when you need to insert an element at a specific index in an array. In such a scenario, you can use the push() method in combination with array slicing.

Here are the steps to insert an element at a specific index in an array:

  1. Create a new empty array.
  2. Copy the elements before the specific index from the original array to the new array.
  3. Add the new element to the new array.
  4. Copy the elements after the specific index from the original array to the new array.

Let’s illustrate these steps with an example. Suppose you have an array of numbers:

And you want to insert the number 3 at index 2 (remember that JavaScript uses zero-based indexing). Here’s how you can accomplish this:

const index = 2; const newNumbers = [ . numbers.slice(0, index), 3, . numbers.slice(index) ]; console.log(newNumbers); // Output: [1, 2, 3, 4, 5] 

In this example, a new array newNumbers is created by copying the elements before index 2 using the slice() method. That’s followed by the new element 3 , and finally you copy the remaining elements after index 2 using the slice() method again. The result is the new array [1, 2, 3, 4, 5] .

The spread operator ( . ) in the example above is used to concatenate the arrays.

But this is not a best approach because you end up using another method ( slice ), making the code difficult for a beginner to understand. Let’s explore how to use the splice method which is more straightfoward.

How to Use the splice() Method to Insert into a JavaScript Array at a Specific Index

The splice() method in JavaScript arrays is used to add or remove elements from an array. You can use the splice() method to insert elements at a specific index in an array.

array.splice(start, deleteCount, item1, item2, . itemN); 
  • array is the array that you want to modify.
  • start is the index where you want to start modifying the array.
  • deleteCount is the number of elements you want to remove from the array, starting at the start index.
  • item1 , item2 , and so on are the elements you want to add to the array at the start index.

For example, let’s say you have an array of numbers:

And you want to insert the number 3 at index 2 . Here’s how you can accomplish this using the splice() method:

numbers.splice(2, 0, 3); console.log(numbers); // Output: [1, 2, 3, 4, 5] 

In this code, the splice() method is called on the numbers array, starting at index 2 , with a deleteCount of 0 . You then add the new element 3 to the array at the start index. The result is the modified array [1, 2, 3, 4, 5] .

Conclusion

In this article, you have learned the two major techniques for inserting elements into a JavaScript array at a specific index.

The splice() method should be your preferred option as it has a better and more straightforward syntax. Knowing these techniques will allow you to manipulate JavaScript arrays more effectively.

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

Источник

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