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


There are multiple ways to insert an item into an array at a specific index in JavaScript:

  • Using the splice() method: The splice() method can be used to add or remove elements from an array. To insert an item at a specific index, we can use the splice() method with the index and 0 as the second argument, followed by the item we want to insert. Here's an example:
let arr = [1, 2, 3, 4];
arr.splice(2, 0, 5);
console.log(arr); // Output: [1, 2, 5, 3, 4]

In the above example, we are inserting the number 5 at index 2 of the array arr.

  • Using the slice() and concat() methods: We can also use the slice() method to split the array into two parts, and then use the concat() method to join the two parts with the item we want to insert. Here's an example:
let arr = [1, 2, 3, 4];
let newArr = arr.slice(0, 2).concat(5, arr.slice(2));
console.log(newArr); // Output: [1, 2, 5, 3, 4]

In the above example, we are splitting the array arr into two parts: [1, 2] and [3, 4]. We then use the concat() method to join the first part with the number 5 and the second part, resulting in the new array [1, 2, 5, 3, 4].

  • Using the unshift() and splice() methods: We can also use the unshift() method to add the item to the beginning of the array, and then use the splice() method to move the item to the desired index. Here's an example:
let arr = [1, 2, 3, 4];
arr.unshift(0);
arr.splice(2, 0, 5);
console.log(arr); // Output: [0, 1, 5, 2, 3, 4]

In the above example, we are adding the number 0 to the beginning of the array using the unshift() method. We then use the splice() method to insert the number 5 at index 2 of the array, resulting in the new array [0, 1, 5, 2, 3, 4].



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.