Open In App

How to insert an item into array at specific index in JavaScript ?

Last Updated : 08 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

To insert an item into the array at a specific index we will break the array from the index and insert the item into the array. There is no inbuilt method in JavaScript that directly allows for the insertion of an element at any arbitrary index of an array. The possible approaches are given below.

Let’s create a JavaScript program having an array, input element, and index.

Javascript
// Given array
let arr = [1, 2, 3, 4, 5];

// Input element
let element = -99;

// Input index
let index = 2;

Examples to insert an item into array at specific index in JavaScript

1. Using array.splice() Method

JavaScript array.splice() Method is an inbuilt method in JavaScript that is used to modify the contents of an array by removing the existing elements and/or by adding new elements.

Syntax:

array.splice(index, no_of_items_to_remove, item1 ... itemX);

Example: In this example, we will insert an element at the 2nd index of the array using the splice() method of JavaScript.

Javascript
function insertElement() {
    let arr = [1, 2, 3, 4, 5];
    let index = 2;
    let element = -99;

    arr.splice(index, 0, element);
    
    console.log(arr);
}

insertElement();

Output
[ 1, 2, -99, 3, 4, 5 ]

Explanation: This insertElement function inserts an element (-99) at a specific index (2) into an array ([1, 2, 3, 4, 5]) using the splice() method. It takes three parameters: the index at which to start changing the array (index), the number of elements to remove (0 in this case), and the new element to add (element). After insertion, it logs the modified array.

2. Using JavaScript for loop

The JavaScript for loop can be used to move all the elements from the index (where the new element is to be inserted) to the end of the array, one place after its current place. The required element can then be placed at the index. 

Syntax: 

// Shift all elements one place to the
// back until index
for (let i = arr.length; i > index; i--) {
    arr[i] = arr[i - 1];
}
// Insert the element at the index
arr[index] = element;

Example: Here, we will insert an element at the 2nd index of the array using the for loop of JavaScript.

Javascript
function insertElement() {
    let arr = [1, 2, 3, 4, 5];
    let index = 2;
    let element = -99;

    // Shift all elements one place
    // to the back until index
    for (let i = arr.length; i > index; i--) {
        arr[i] = arr[i - 1];
    }

    // Insert the element at the index
    arr[index] = element;

    console.log(arr);
}

insertElement();

Output
[ 1, 2, -99, 3, 4, 5 ]

Explanation: This insertElement function inserts an element (-99) at a specific index (2) into an array ([1, 2, 3, 4, 5]). It shifts all elements after the index one place to the back to make room for the new element and then inserts the element at the index. Finally, it logs the modified array.

3. Using the concat method

The JavaScript concat method is used to merge two or more arrays together. This method does not alter the original arrays passed as arguments but instead, returns a new Array.

Syntax:

let newArray1 = oldArray.concat()
let newArray2 = oldArray.concat(value0)
let newArray3 = oldArray.concat(value0,value1)
.......
.......
let newArray = oldArray.concat(value1 , [ value2, [ ...,[ valueN]]])

Example: Here, we have used concat method.

Javascript
function insertItemAtIndex(arr, index, item) {
  if (index < 0 || index > arr.length) {
    // Index out of bounds, 
    // return the original array
    return arr;
  }

  return arr.slice(0, index)
    .concat(item, arr.slice(index));
}

// Example usage:
const originalArray = [1, 2, 3, 4, 5];
const newArray = insertItemAtIndex(originalArray, 2, -99);
console.log(newArray); 

Output
[ 1, 2, -99, 3, 4, 5 ]

Explanation: This JavaScript function insertItemAtIndex takes an array, an index, and an item as parameters. It checks if the index is within bounds, then inserts the item at the specified index using the slice() method to create a new array with the item inserted, and returns the modified array.

4.Using spread syntax and array slicing

To insert an item at a specific index in JavaScript, combine spread syntax and array slicing. Create a new array by slicing before and after the index, then spread the new item between them.

Example: In this example the spread syntax is used to create a new array that includes the items before the specified index, the new item, and the items after the specified index.

JavaScript
let arr = [1, 2, 3, 5];
const index = 3;
const newItem = 4;

arr = [...arr.slice(0, index), newItem, ...arr.slice(index)];

console.log(arr);

Output
[ 1, 2, 3, 4, 5 ]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads