Skip to content
the poor coder

add element in the middle of array javascript

Poor Man
Published
Reading time
2 min read
On this page

Adding Element in the Middle of Array in Javascript#

There may be times when you need to add an element in the middle of an array in Javascript. Here are a few ways to do so:

Using the splice() Method#

The splice() method can be used to add an element to an array at a specific index. Here’s how:

Text

let myArray = [1, 2, 4, 5];
myArray.splice(2, 0, 3); // Adds element 3 at index 2
console.log(myArray); // Output: [1, 2, 3, 4, 5]

The first parameter of the splice() method specifies the index where the element should be added. The second parameter specifies how many elements should be removed (in this case, we’re not removing anything). The third parameter specifies the element that should be added.

Using the concat() Method#

The concat() method can be used to join two arrays together. Here’s how:

Text

let myArray = [1, 2, 4, 5];
let newArray = myArray.slice(0, 2).concat(3, myArray.slice(2));
console.log(newArray); // Output: [1, 2, 3, 4, 5]

We first slice the original array to get everything up to the index where we want to add the new element. We then use concat() to join that sliced array with the new element and the rest of the original array.

Using the spread operator#

The spread operator can also be used to add an element to an array at a specific index. Here’s how:

Text

let myArray = [1, 2, 4, 5];
let newArray = [...myArray.slice(0, 2), 3, ...myArray.slice(2)];
console.log(newArray); // Output: [1, 2, 3, 4, 5]

This code also slices the original array and uses the spread operator to join the sliced arrays with the new element.

Conclusion#

These are just a few ways to add an element in the middle of an array in Javascript. Each method has its own advantages and disadvantages depending on the situation. Use whichever method suits your needs.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC