• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Justin Joyce

Practical tips and tutorials about software development.

  • Standing Invitation
  • Featured Posts
  • Latest
  • About

Insert into javascript array at a specific index

Posted Feb 1, 2023 — Updated Jan 10, 2024

There are two options when inserting into an array in javascript: slice() and splice().

Array.prototype.slice

Array.prototype.slice returns a copy of a portion of an array, like so:

const myArray = ["a", "b", "d", "e", "f"];

// Slice starting at [0], and take 2 elements
myArray.slice(0, 2) // ["a", "b"]

// if you don't pass a second argument,
// slice will go all the way to the end of the array
myarray.slice(2) // ["d", "e", "f"]

Let’s say we want to insert c where it belongs in this list, between b and d.

const originalArray = ["a", "b", "d", "e", "f"];

const newArray = [...myArray.slice(0, 2), "c", ...myArray.slice(2)];

// newArray looks good
console.log(newArray); // ["a", "b", "c", "d", "e", "f"]

// originalArray hasn't changed
console.log(originalArray); // ["a", "b", "d", "e", "f"]

The three dots ... in the above example are known as javascript spread syntax, and are frequently used for expanding arrays like this.

Array.prototype.splice

In the slice example, the original array remained unchanged; we created a new copy. Array.prototype.splice, however, will modify the original array in place.

const originalArray = ["a", "b", "d", "e", "f"];

// The 0 here means "don't delete any elements" (another use of splice)
originalArray.splice(2, 0, "c");

console.log(originalArray); // ["a", "b", "c", "d", "e", "f"];

Modifying arrays in place can be a dangerous operation. If you have an array which is imported into multiple project files and one of them calls .splice() on it, it’ll change the value everywhere. For that reason, I generally prefer to use slice for something like this; I like to keep my objects immutable.

Filed Under: Arrays, Javascript

Primary Sidebar

Recent Posts

  • Every Built-In Vim Color Scheme (with screenshots)
  • Reverse a string in Python
  • Meeting Cost Calculator
  • Vim find and replace
  • What makes an effective development team

Categories

  • Arrays (5)
  • Command Line (9)
  • Dates (3)
  • Featured (7)
  • Git (7)
  • Golang (5)
  • Javascript (8)
  • Productivity (8)
  • Projects (4)
  • Python (15)
  • Regex (2)
  • Ruby (3)
  • Shell (2)
  • Thoughts (2)
  • Tips (11)
  • Tools (3)
  • Tutorials (1)
  • Vim (4)

Archives

  • July 2024 (1)
  • February 2024 (1)
  • January 2024 (1)
  • December 2023 (1)
  • November 2023 (1)
  • October 2023 (4)
  • September 2023 (1)
  • August 2023 (2)
  • July 2023 (5)
  • June 2023 (3)
  • May 2023 (6)
  • April 2023 (5)
  • March 2023 (5)
  • February 2023 (10)
  • January 2023 (6)
  • December 2022 (7)

Copyright © 2025 · Contact me at justin [at] {this domain}

  • Privacy Policy