Open In App

JavaScript - Insert Elements at a Given Position in an JS Array

Last Updated : 13 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To insert an element at a specific position in a JavaScript array, the JS splice() method is used.

JavaScript
let a = [10, 20, 30, 40];
let e = 50;
let i = 2;
a.splice(i - 1, 0, e);
console.log(a);

Output
[ 10, 50, 20, 30, 40 ]

Using built-in Method

The JavaScript splice() method is used to insert elements at a specific position in JS Array.

JavaScript
let a = [10, 20, 30, 40];
a.splice(4, 0, 50);
console.log(a);

Output
[ 10, 20, 30, 40, 50 ]

Writing Your Own Method

To add an element at a given index in an array, shift all the elements from that index to the right and then insert the new element at the required index.

JavaScript
let a = [10, 20, 30, 40];
let e = 50;

let p = 2;

// Shifting elements to the right
for (let i = a.length; i >= p; i--)
    a[i] = a[i - 1];

// Insert the new element at index pos - 1
a[p - 1] = e;

console.log(a);

Output
[ 10, 50, 20, 30, 40 ]

Next Article

Similar Reads