splice CODE
Function
splice
changes content of an array. Let's first create an array of integers
let myFavoriteNumbers = [5, 14, 16, 18, 23, 25, 27, 50, 70]
If we want to remove one element from an array, we need to pass
1
as the second argument and the index of the item as the first argument. In this example
14
(second item) will be removed by passing
1 and 1
as arguments
myFavoriteNumbers.splice(1, 1);  // [5, 16,18, 23, 25, 27, 50, 70]
To remove two adjacent items, we need to pass first item's index
2
and quantity of items
2
that we want to remove. In this example we want to remove
18
and
23
from the array at the same time
myFavoriteNumbers.splice(2, 2);  // [5, 16, 25, 27, 50, 70]
Replaces 3 items starting from index 2 with
27
,
29
and
31
myFavoriteNumbers.splice(2, 2, 27, 29, 31);  // [5, 16, 27, 29, 31, 50, 70]
Removes all the items of the array except the first and the last items
myFavoriteNumbers.splice(1, 5);  // [5,70]
Adds the two new items
100
and
200
to the array after the first item
myFavoriteNumbers.splice(1, 0, 100, 200);  // [5, 100, 200, 70]
by Valeri Tandilashvili
4 years ago
JavaScript
Array functions
1
Pro tip: use ```triple backticks around text``` to write in code fences