Skip to content

WebDevHubs

  • Home
  • HTML
  • CSS
  • JavaScript
  • Web Technologies
  • Web Templates
  • Toggle search form

How to Insert an Item into an Array at a Specific Index in JavaScript?

Posted on December 5, 2024March 20, 2025 By Admin No Comments on How to Insert an Item into an Array at a Specific Index in JavaScript?

Given an array and index, the task is to insert a particular item at a given index. There are multiple ways to insert an item into an array at a specific index in JavaScript.

1. Using splice() Method

The splice() method is used to modify the original array. This method can be used to insert, remove, or replace elements in an array.

const arr = [10, 20, 30, 40, 50];

// Insert 25 at index 2
arr.splice(2, 0, 25);

console.log(arr);
// Output: [ 10, 20, 25, 30, 40, 50 ]

2. Using Spread Operator (…)

The spread operator is used to create a new array by spreading the existing array elements and adding new items at specific positions.

const arr = [10, 20, 30, 40, 50];

// Insert 25 at index 2
const newArr = [...arr.slice(0, 2), 25, ...arr.slice(2)];

console.log(newArr); 
// Output: [ 10, 20, 25, 30, 40, 50 ]

3. Using for Loop

We can also use for loop to insert an item at given index in an array. The for loop can be used to shift the array elements and insert the new item.

const arr = [10, 20, 30, 40, 50];
const index = 2;
const newItem = 25;

// Shift elements to the right
for (let i = arr.length; i > index; i--) {
    arr[i] = arr[i - 1];
}

// Insert the new item
arr[index] = newItem;

console.log(arr);
// Output: [ 10, 20, 25, 30, 40, 50 ]

4. Using Array concat() Method

The concat() method combines multiple arrays into one array. It is suitable for inserting an item by combining slices of the original array with the new item.

const arr = [10, 20, 30, 40, 50];
const newItem = 25;

const newArr = arr.slice(0, 2)
                  .concat(newItem)
                  .concat(arr.slice(2));

console.log(newArr); 
// Output: [ 10, 20, 25, 30, 40, 50 ]
JavaScript, Web Technologies Tags:JavaScript-Questions

Post navigation

Previous Post: JavaScript Array indexOf() Method
Next Post: Design an Identity Card using HTML and CSS with Source Code

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Archives

  • June 2025
  • May 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024

Categories

  • CSS
  • HTML
  • JavaScript
  • Lodash
  • PHP
  • Python
  • Web Technologies
  • Web Templates

Recent Posts

  • JavaScript Array isArray() Method
  • JavaScript Array forEach() Method
  • JavaScript Array includes() Method
  • JavaScript Array keys() Method
  • JavaScript Array lastIndexOf() Method

Recent Comments

No comments to show.

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme