Skip to main content

Command Palette

Search for a command to run...

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

Javascript | Arrays | insert | splice | how to

Published
1 min read
V

Graduated with a Master’s degree in Software Engineering from San Jose State University in December 2019 and currently working at PayPal on the Customer Journey Platform. I enjoy generating new ideas and devising feasible solutions to broadly relevant problems. My colleagues would describe me as a driven, resourceful individual who maintains a positive, proactive attitude when faced with adversity. Interested to work in areas related to Distributed Systems, Cloud Infrastructure and Micro-Services. I get a lot of satisfaction from the constant learning and puzzle solving that comes with my profession and contributing to a successful and worthwhile product. My expertise includes project design and management, data analysis and interpretation, and the development and implementation of software products.

You want the splice function on the native array object.

arr.splice(index, 0, item) will insert item into arr at the specified index (deleting 0 items first and then insert item at index).

In this example we will create an array and add an element to it into index 2:

let arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

console.log(arr.join()); // Jani, Hege, Stale, Kai Jim,Borge
arr.splice(2, 0, "Lene");
console.log(arr.join()); // Jani, Hege, Lene, Stale, Kai Jim, Borge

Why is it called splice and not insert or remove?

Splice means to join or connect, also to change. You have an established array that you are now "changing" which would involve adding or removing elements.