Skip to main content

Command Palette

Search for a command to run...

Splice in JavaScript

Updated
β€’2 min read
Splice in JavaScript
S

I am Senior Frontend Engineer and post daily tips about Web Dev

My goal is to encourage more people to get into tech.

The splice method changes the content of the array in place and can be used to add or remove items from the array.

const arr = ["🌼", "🌴", "🌹", "🌡", "πŸ„"];
arr.splice(2,3); // ["🌹", "🌡", "πŸ„"]
console.log(myArr); // ["🌼", "🌴"]</span>

Syntax:

let arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])</span>

start specifies index at which to start changing the array.

If start is greater than the length of the array, then start will be set to the length of the array. i.e no element will be deleted.

If start is negative, it will begin that many elements from the end of the array.

In deleteCount, The number of items you want to remove.

In item, The number you want to add(If you're removing, you can just leave this blank).

NOTE: Splice always return an array containing the deleted elements.

🌚 When only one argument is provided, all the items after the provided starting index are removed from the array:

const arr = ["🌼", "🌴", "🌹", "🌡", "πŸ„"];
arr.splice(2); // ["🌹", "🌡", "πŸ„"]
console.log(myArr); // ["🌼", "🌴"]</span>

🌚 Remove 1 element at index 3:

const arr = ["🌼", "🌴", "🌹", "🌡", "πŸ„"];
arr.splice(3, 1); // ["🌡"]
console.log(myArr); // ["🌼", "🌴", "🌹", "πŸ„"]</span>

🌚 An arbitrary amount of additional arguments can be passed-in and will be added to the array:

const arr = ["🌼", "🌴", "🌹", "🌡", "πŸ„"];
arr.splice(2, 1, "⭐️", "πŸ’₯"); // ["🌹"]
console.log(myArr); // ["🌼", "🌴", "⭐️", "πŸ’₯", "🌡", "πŸ„"]</span>

🌚 Remove 1 element from index -2:

const arr = ["🌼", "🌴", "🌹", "🌡", "πŸ„"];
arr.splice(-2, 1); // ["🌡"]
console.log(myArr); // ["🌼", "🌴", "🌹", "πŸ„"]</span>

🌚 You can specify 0 as the number of items to remove to simply add new items at the specified location in the array:

const arr = ["🌼", "🌴", "🌹", "🌡", "πŸ„"];
arr.splice(2, 0, "⭐️", "πŸ’₯"); // []
console.log(myArr); // ["🌼", "🌴", "⭐️", "πŸ’₯", "🌹", "🌡", "πŸ„"]</span>

🌚 Add few items at the end of array:

const arr = ["🌼", "🌴", "🌹", "🌡", "πŸ„"];
arr.splice(arr.length, 0, "πŸŒ•", "🌞", "🌦"); // []
console.log(myArr); // ["🌼", "🌴", "🌹", "🌡", "πŸ„", "πŸŒ•", "🌞", "🌦"]</span>

Reference 🧐

Splice MDN

🌟 Twitter | πŸ‘©πŸ»β€πŸ’» Suprabha.me | 🌟 Instagram

D

Hi, Thanks for the full and clear article. I'm a Data Science enthusiast working on my second summer course program for high schoolers who want to learn JavaScript fast. Because of the lack of online teachers, I'll be hiring freelancers who have at least some experience. If interested, please share your personal portfolio page and contact email. JavaScript - Array splice() Method >> my lab assignment https://essays.agency/lab-report.html