1let arr = ['foo', 'bar', 10, 'qux'];
2
3// arr.splice(<index>, <steps>, [elements ...]);
4
5arr.splice(1, 1); // Removes 1 item at index 1
6// => ['foo', 10, 'qux']
7
8arr.splice(2, 1, 'tmp'); // Replaces 1 item at index 2 with 'tmp'
9// => ['foo', 10, 'tmp']
10
11arr.splice(0, 1, 'x', 'y'); // Inserts 'x' and 'y' replacing 1 item at index 0
12// => ['x', 'y', 10, 'tmp']
1/*splice(start)
2splice(start, deleteCount)
3splice(start, deleteCount, replaceitem1)
4splice(start, deleteCount, replaceitem1, ""2, ""N) */
5
6
7//examples
8const months = ['Jan', 'March', 'April', 'June'];
9months.splice(1, 0, 'Feb');
10// inserts at index 1
11console.log(months);
12// expected output: Array ["Jan", "Feb", "March", "April", "June"]
13
14months.splice(4, 1, 'May');
15// replaces 1 element at index 4
16console.log(months);
17// expected output: Array ["Jan", "Feb", "March", "April", "May"]
18
19
20
1let colors = ['red', 'blue', 'green'];
2
3let index_element_to_be_delete = colors.indexOf('green');
4
5colors.splice(index_element_to_be_delete);
6
7//Colors now: ['red', 'blue']
1const months = ['Jan', 'March', 'April', 'June'];
2months.splice(1, 0, 'Feb');
3// inserts at index 1
4console.log(months);
5// expected output: Array ["Jan", "Feb", "March", "April", "June"]
6
7months.splice(4, 1, 'May');
8// replaces 1 element at index 4
9console.log(months);
10// expected output: Array ["Jan", "Feb", "March", "April", "May"]
11
12months.splice(0, 1);
13// removes 1 element at index 0
14console.log(months);
15// expected output: Array ["Feb", "March", "April", "May"]
1const numbers = [10, 11, 12, 12, 15];
2const startIndex = 3;
3const amountToDelete = 1;
4
5numbers.splice(startIndex, amountToDelete, 13, 14);
6// the second entry of 12 is removed, and we add 13 and 14 at the same index
7console.log(numbers);
8// returns [ 10, 11, 12, 13, 14, 15 ]
9
1let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
2//insert new element into array at index 2
3let removed = myFish.splice(2, 0, 'drum')
4
5// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
6// removed is [], no elements removed