DEV Community

Cover image for How to insert an element at a specific array index with JavaScript
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

How to insert an element at a specific array index with JavaScript

In this article, I'll teach you how to add an element to a JavaScript array but set it to a specific position.

Let's set the stage. I have a sidebar menu with a couple of items in it.

const sidebarMenu = ['home', 'about', 'contact'];
Enter fullscreen mode Exit fullscreen mode

However, for premium users, I want to add the courses menu. It has to show right before the contact item.

Add an element to an array at a specific index with JavaScript

To add this item, we can use the splice method. This method has multiple powers and can even be used to delete items.
So be very careful when setting the parameters.

To set an item, we can use the first parameters to define the position, and everything after that is the items we push.

if (premiumUser) {
  sidebarMenu.splice(2, 0, 'courses');
}
Enter fullscreen mode Exit fullscreen mode

Our sidebarMenu now has the following content: [ 'home', 'about', 'courses', 'contact' ].

So let's see what the numbers mean:

  • the first one (2): start position
  • second one (0): delete count
  • the rest: items to add

It's important to note that JavaScript arrays start at zero, so when defining the start position, you must keep that in mind.

Our array counts like this:

  • 0: Home
  • 1: About
  • 2: Contact

With the splice method, we technically say:
Add an item at position two, don't remove any existing elements, and the element to add is 'courses'.

Adding multiple elements

A super cool thing about splice is that it has no limit to how many items it can add.
So we can even add multiple items.

if (premiumUser) {
  sidebarMenu.splice(2, 0, 'courses', 'profile');
}

// [ 'home', 'about', 'courses', 'profile', 'contact' ]
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (2)

Collapse
 
lexlohr profile image
Alex Lohr

Two small additions:

  1. You can use the spread operator to insert an array of values.
  2. Using Array.prototype.splice has a considerable performance impact; if not used sparingly, this can really slow down your app. Alternatives include using a sparse array (so each item has its own position and the change can happen by assignment) or a Set (so there are no positions to shift around).
Collapse
 
dailydevtips1 profile image
Chris Bongers

Thanks Alex,

Good point indeed.
I think when you need to use this on large data sets you should indeed consider alternatives.
However for these small arrays If not really noticed much negative slow speeds.