Categories
arrays javascript

How to insert an item into an array at a specific index (JavaScript)

3867

I am looking for a JavaScript array insert method, in the style of:

arr.insert(index, item)

Preferably in jQuery, but any JavaScript implementation will do at this point.

5

  • 139

    Note that JQuery is a DOM and event manipulation library, not a language of its own. It has nothing to do with array manipulation.

    – Domino

    Feb 18, 2015 at 15:36

  • 29

    api.jquery.com/jQuery.inArray has nothing to do with the DOM or events. jQuery has evolved into a mixed toolkit for in browser JS development, leading to people expecting it to have a method for everything.

    – Tim

    Apr 14, 2016 at 8:14

  • 7

    @Tim, But it’s still not a language of its own (still there are some questions like “how to sum two numbers in jQuery” here on SO)

    – Victor

    May 7, 2018 at 13:31

  • 7

    @Victor No, and never will be. jQuery was useful and relevant, but it’s had its day.

    – Tim

    May 8, 2018 at 6:17

  • I’m annoyed that the title of this question and its page title are different (jQuery vs. JS). Shows up differently in search results.

    – Andrew

    Jun 7, 2020 at 0:14

6209

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, that is, it’s just an insert).

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

var 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

21

  • 237

    Thanks, I thought I would feel stupid for asking but now that I know the answer I don’t! Why on earth did they decide to call it splice when a more searchable term was in common use for the same function?!

    – tags2k

    Feb 25, 2009 at 14:46

  • 104

    @tags2k: because the function does more than inserting items and it’s name was already established in perl?

    – Christoph

    Feb 25, 2009 at 14:53

  • 18

  • 71

    Splice can insert, but just as frequently does not. For example: arr.splice(2,3) will remove 3 elements starting at index 2. Without passing the 3rd….Nth parameters nothing is inserted. So the name insert() doesn’t do it justice either.

    – EBarr

    May 13, 2014 at 1:45

  • 21

    I think the term “splice” makes sense. 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. You specify where in the array to start, then how many old items to remove (if any) and lastly, optionally a list of new elements to add. Splice is also a great sci-fi term of course.

    Nov 21, 2014 at 15:45

377

You can implement the Array.insert method by doing this:

Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};

Then you can use it like:

var arr = [ 'A', 'B', 'D', 'E' ];
arr.insert(2, 'C');

// => arr == [ 'A', 'B', 'C', 'D', 'E' ]

9

  • 17

    To insert multiple items you can use Array.prototype.insert = function (index, items) { this.splice.apply(this, [index, 0].concat(items)); }

    May 30, 2014 at 12:15


  • 7

    The problem with adding stuff to array is that the function will show up as an element when you do for(i in arr) {…}

    – rep_movsd

    Jul 2, 2014 at 9:38

  • 17

    But keep in mind that it’s not recommended to extend native types since it might interfere with other code or future functionality.

    – marsze

    Aug 21, 2018 at 9:48

  • 70

    Don’t modify objects you don’t own

    Feb 19, 2019 at 18:09

  • 22

    Don’t modify prototypes

    – satya164

    May 31, 2019 at 12:54

252

Other than splice, you can use this approach which will not mutate the original array, but it will create a new array with the added item. It is useful, when you need to avoid mutation. I’m using the ES6 spread operator here.

const items = [1, 2, 3, 4, 5]

const insert = (arr, index, newItem) => [
  // part of the array before the specified index
  ...arr.slice(0, index),
  // inserted item
  newItem,
  // part of the array after the specified index
  ...arr.slice(index)
]

const result = insert(items, 1, 10)

console.log(result)
// [1, 10, 2, 3, 4, 5]

This can be used to add more than one item by tweaking the function a bit to use the rest operator for the new items, and spread that in the returned result as well:

const items = [1, 2, 3, 4, 5]

const insert = (arr, index, ...newItems) => [
  // part of the array before the specified index
  ...arr.slice(0, index),
  // inserted items
  ...newItems,
  // part of the array after the specified index
  ...arr.slice(index)
]

const result = insert(items, 1, 10, 20)

console.log(result)
// [1, 10, 20, 2, 3, 4, 5]

6

  • 2

    Is this a good, safe way to do this? I ask because this seems so elegant and concise but no other answers touch upon this. Most of them modify the prototype object!

    Dec 11, 2017 at 9:32

  • 9

    @HarshKanchina That’s probably because most of the answers are pre ES6, but this approach is very common now from my experience

    – gafi

    Dec 16, 2017 at 22:35


  • 1

    This approach will always be slower and worse than splice. Don’t be fooled by the pretty sugar syntax or the popularity among other misguided devs (*cough* gafi *cough*). Allocating a whole new array and discarding the old array is way slower than modifying the original array. If you need a copy, then call slice() before splice(). Never use the ES6 for such trivial things which can be done far better and far more cleanly with other APIs.

    – Jack G

    Jan 19, 2021 at 2:19

  • 3

    You should explain WHY you should avoid mutation. Is it slow? If so, how much slower? Is it worth the extra “hassle”?

    May 25, 2021 at 9:34

  • 1

    @JackG don’t forget that slice() will allocate a new array, and indeed, splice() allocates a new array too since it returns an array of the items that were removed (an empty array in this case). Running a benchmark on these cases shows that splice is quicker (by ~30%), but we’re in the range of millions of operations per second, so unless your application is doing a lot of these operations in a tight loop, it’s not going to make any difference.

    – nickf

    Sep 22, 2021 at 9:00