How to Insert Elements at Specific Index of Array

In this blog, I will discuss various possible methods in JavaScript to insert an element at a specific index of array. Out of all the methods splice is my most favorite as it is the shortest to write. I have discussed other methods that will help you learn various array methods which might be useful in solving various kind of other coding problems.

Using Splice Method:
You can use the splice() method in JavaScript to insert an element at a specific index of an array. This method is versatile; you can use it to delete or insert an element at a specific index or even to delete or insert multiple elements starting from any array index. It’s a truly a valuable array method in JavaScript that you must learn.

splice method is used to change the contents of an array by deleting existing elements or adding new elements. To insert an element at a specific position in an array using splice, you can provide the index at which you want to start modifying the array, specify the number of elements to delete (which is 0 for insertion), and then provide the elements you want to insert.

Here’s the basic syntax for using splice to insert an element into an array:

array.splice(startIndex, deleteCount, item1, item2, ...);

startIndex: The index at which to start changing the array.

deleteCount: The number of elements to remove from the array. If set to 0, no elements are removed.

item1, item2, ...: Elements to add to the array.

// Example
let animals = ['lion', 'tiger', 'elephant', 'zebra'];
let newIndex = 2; // Index at which to insert the element
let newAnimal = 'giraffe';

animals.splice(newIndex, 0, newAnimal);

console.log(animals); // Output: ['lion', 'tiger', 'giraffe', 'elephant', 'zebra']

You can also use splice to delete element or replace element at specific index . You can do this by specifying a non-zero value for deleteCount and providing new elements in place.

Without Splice Method:
If you prefer not to use the splice method, you can create an empty newArray and store the elements up to that index (exclusive), at which we want to insert the value, in this newArray. Next, push the desired element at the specified index, and then push the remaining elements of the array into this newArray. Finally, assign this modified newArray back to the original array.

// Example with numbers array
let numbers = [1, 2, 4, 5];
let newIndex = 2; // Index at which to insert the element
let newValue = 3;

let newArray = [];
for (let i = 0; i < newIndex; i++) {
  newArray.push(numbers[i]);
}
newArray.push(newValue);
for (let i = newIndex; i < numbers.length; i++) {
  newArray.push(numbers[i]);
}

numbers = newArray;

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

Swapping Elements Approach:
Another approach involves pushing the desired element into the array first. Then, perform a swap between adjacent elements starting from the end and continuing until the element reaches the desired insertion index.

// Example with animals array
let animals = ['lion', 'tiger', 'elephant', 'zebra'];
let newIndex = 2; // Index at which to insert the element
let newAnimal = 'giraffe';

animals.push(newAnimal); // Add element at the end

for (let i = animals.length - 1; i > newIndex; i--) {
  [animals[i],animals[i-1]] = [animals[i - 1], animals[i]];
}

console.log(animals); // Output: ['lion', 'tiger', 'giraffe', 'elephant', 'zebra']

Shifting Elements Approach:
A variation of the previous method involves adding a placeholder (e.g., zero) to the end of the array. Next, run a loop starting from the end, shifting each element one index to the right. Once a vacant space is created at the desired index, assign the desired value to that index.

// Example with numbers array
let numbers = [1, 2, 4, 5];
let newIndex = 2; // Index at which to insert the element
let newValue = 3;

numbers.push(0); // Add a temporary element at the end

for (let i = numbers.length - 1; i > newIndex; i--) {
  numbers[i] = numbers[i - 1];
}
numbers[newIndex] = newValue;
numbers.pop(); // Remove the temporary element

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

Using Slice and Destructuring:
An alternative approach is to use the slice method and array destructuring together. This allows you to insert an element at a specific index without directly modifying the original array, providing a concise and readable solution.

Learn more about spread operator here.

// Example with animals array
let animals = ['lion', 'tiger', 'elephant', 'zebra'];
let newIndex = 2; // Index at which to insert the element
let newAnimal = 'giraffe';

animals = [...animals.slice(0, newIndex), newAnimal, ...animals.slice(newIndex)];
console.log(animals); // Output: ['lion', 'tiger', 'giraffe', 'elephant', 'zebra']

Using concat and slice method:
You can utilize the slice method along with concat to insert an element at a specific index. We take an empty new array then concatenate the sliced array from the beginning up to the desired index with the new array. Then concatenate the element itself. Finally, concatenate the rest of the original array. Here’s an example using animal names:

// Original array
let animals = ['lion', 'tiger', 'elephant', 'giraffe'];

// Element to insert
let newAnimal = 'zebra';

// Index to insert at
let insertIndex = 2;

// Inserting the new animal at the specified index
animals = [].concat(animals.slice(0, insertIndex), newAnimal, animals.slice(insertIndex));

Using Array.from:
You can use Array.from to create a new array with the element inserted at the desired index.

// Original array
let animals = ["lion", "tiger", "elephant", "giraffe"];

// Element to insert
let newAnimal = "zebra";

// Index to insert at
let insertIndex = 2;

// Inserting the new animal at the specified index using Array.from
let newArray = Array.from({ length: animals.length + 1 }, (value, index) =>
  index === insertIndex ? newAnimal : animals[index - (index > insertIndex)]
);
console.log(newArray); //[ 'lion', 'tiger', 'zebra', 'elephant', 'giraffe' ]

In this example, we use Array.from to create a new array with the desired length. The callback function is used to fill in the values. If the current index is equal to the insertIndex, we insert the new element. Otherwise, we copy the element from the original array to the new array, adjusting the index to account for the insertion

Using Array.prototype.reduce:
You can leverage the reduce function to build a new array with the element inserted at the desired index. This approach involves iterating over the original array and constructing a new array by checking the current index. Here’s an example using numbers:

// Original array
let numbers = [1, 2, 4, 5];

// Element to insert
let newNumber = 3;

// Index to insert at
let insertIndex = 2;

// Inserting the new number at the specified index using reduce
let newArray = numbers.reduce((acc, value, index) => {
  if (index === insertIndex) {
    acc.push(newNumber);
  }
  acc.push(value);
  return acc;
}, []);
console.log(newArray); //[ 1, 2, 3, 4, 5 ]

In this example, the reduce function is used to build a new array. If the current index matches the specified insert index, the new element is pushed into the array. Otherwise, the original element is pushed. The resulting array contains the new element at the desired index.

Using Array.prototype.map :

The map method is not the most appropriate choice for inserting an element at a specific index into an array, as it is designed to create a new array based on the existing one without modifying the original array. The map method is mainly used for transforming each element in an array. But if you want to use it to insert an element at specific index , you can.

// Original array
let animals = ["lion", "tiger", "elephant", "giraffe"];

// Element to insert
let newAnimal = "zebra";

animals.push("");
// Index to insert at
let insertIndex = 3;

// Inserting the new animal at the specified index using map

let newArray = animals.map((value, index) =>
  index === insertIndex ? newAnimal : animals[index - (index > insertIndex)]
);

console.log(newArray); //[ 'lion', 'tiger', 'elephant', 'zebra', 'giraffe' ]

or you can use nested ternary operator.

// Original array
let animals = ["lion", "tiger", "elephant", "giraffe"];

// Element to insert
let newAnimal = "zebra";

animals.push("");
// Index to insert at
let insertIndex = 3;

// Inserting the new animal at the specified index using map
let newArray = animals.map((value, index) =>
  index === insertIndex
    ? newAnimal
    : index < insertIndex
    ? value
    : animals[index - 1]
);

console.log(newArray); //[ 'lion', 'tiger', 'elephant', 'zebra', 'giraffe' ]

These methods provide different ways to achieve the same result, and the choice of method depends on your specific use case and coding preferences.

You can learn various array methods in JavaScript here .

Don't Miss Out! Subscribe to Read Our Latest Blogs.

If you found this blog helpful, share it on social media.

Subscription form (#5)

Leave a Comment

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

Pin It on Pinterest

Scroll to Top