Splice in JavaScript

Splice in JavaScript

ยท

2 min read

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

Did you find this article valuable?

Support Suprabha's Blog by becoming a sponsor. Any amount is appreciated!