Insert an item in the middle of an array?

rusty1_rusty1 asked this question 5 months ago
rusty1_rusty1 on Feb 18

I need to insert an object into the middle of an existing array of objects.

How can I do that with JavaScript? The method used should work regardless of how large the array is.

4 suggested answers
nick on Mar 19

You'll want to use the JavaScript splice() method.

Here's what it would look like:

let array = ["zero", "one", "two", "three", "four", "five"];

array.splice(array.length / 2, 0, "middle");

// array = ["zero", "one", "two", "middle", "three", "four", "five"]

array.length / 2 gets the middle index position in the array, which means the "middle" string will be inserted into the middle of the array.

0 replies
itsbambi on Mar 19
array.splice(middleIndex, 0, newItem);
0 replies
moon_man41 on Mar 19

Here's a prototype method you can apply to any array in code:

Array.prototype.insertInMiddle = function (newItem) {
  this.splice(this.length / 2, 0, newItem);

You'd use it like this:

let array = ["A", "B", "D", "E"];

// array = ["A", "B", "C", "D", "E"];
0 replies
coderguy on Mar 19

Here's an ES6 method that inserts one or more items into an array at a given index:

const insert = (arr, index, ...newItems) => [
  ...arr.slice(0, index),

Then you could insert one or more items into the middle of an array like this:

const myArray = [1, 2, 3, 4, 5, 6]

const result = insert(myArray, myArray.length / 2, "middle", "middle")
// result = [1, 2, 3, "middle", "middle", 4, 5, 6]
0 replies