This content originally appeared on Level Up Coding - Medium and was authored by Suprabha Supi
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); // ["?", "?"]
Syntax:
let arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
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 returns 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); // ["?", "?"]
? Remove 1 element at index 3:
const arr = ["?", "?", "?", "?", "?"];
arr.splice(3, 1); // ["?"]
console.log(myArr); // ["?", "?", "?", "?"]
? 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); // ["?", "?", "⭐️", "?", "?", "?"]
? Remove 1 element from index -2:
const arr = ["?", "?", "?", "?", "?"];
arr.splice(-2, 1); // ["?"]
console.log(myArr); // ["?", "?", "?", "?"]
? 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); // ["?", "?", "⭐️", "?", "?", "?", "?"]
? Add few items at the end of array:
const arr = ["?", "?", "?", "?", "?"];
arr.splice(arr.length, 0, "?", "?", "?"); // []
console.log(myArr); // ["?", "?", "?", "?", "?", "?", "?", "?"]
Reference ?
? Twitter | ??? Suprabha.me | ? Instagram
Splice in JavaScript was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Suprabha Supi
Suprabha Supi | Sciencx (2021-06-29T00:30:28+00:00) Splice in JavaScript. Retrieved from https://www.scien.cx/2021/06/29/splice-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.