8 3 1 common array methods 2f 2f splice examples 28 splice 29

Solutions on MaxInterview for 8 3 1 common array methods 2f 2f splice examples 28 splice 29 by the best coders in the world

showing results for - "8 3 1 common array methods 2f 2f splice examples 28 splice 29"
Youssef
27 Nov 2019
1//The general syntax for this method is:
2arrayName.splice(index, number of elements to change, item1, item2, ...);
3
4//Inside the parentheses (), only the first argument is required.
5
6/*The splice method modifies one or more elements anywhere in the array. 
7Entries can be added, removed, or changed. This method requires 
8practice.*/
9
10/*To remove elements from an array, the splice method needs 1 or 2 
11arguments.
12
13Given only one argument, splice(index) removes every entry from index
14to the end of the array.*/
15let arr = ['a', 'b', 'c', 'd', 'e', 'f'];
16
17arr.splice(2);    //Everything from index 2 and beyond is removed.
18console.log(arr);
19
20//['a', 'b']
21
22
23/*With two arguments, splice(index, number of items) starts at index 
24and removes the specified number of items from the array.*/
25let arr = ['a', 'b', 'c', 'd', 'e', 'f'];
26
27arr.splice(2,3);    //Start at index 2 and remove 3 total entries.
28console.log(arr);
29
30arr.splice(1,1);    //Start at index 1 and remove 1 entry.
31console.log(arr);
32
33//[ 'a', 'b', 'f' ]
34//[ 'a', 'f' ]
35
36
37/*To add or replace elements in an array, the splice method requires
383 or more arguments.
39
40To add elements, set the number of elements argument to 0 and follow
41this with the new items.*/
42
43//Example: 
44/*splice(index, 0, new item) starts at index and INSERTS the new items.
45Existing elements get shifted further down the array.*/
46let arr = ['a', 'b', 'c', 'd', 'e', 'f'];
47
48arr.splice(2,0,'hello');     //Start at index 2, remove 0 entries, and add 'hello'.
49console.log(arr);
50
51//[ 'a', 'b', 'hello', 'c', 'd', 'e', 'f' ]
52
53
54/*To replace elements in an array, the number of elements argument 
55must be a positive integer. Follow this with the new items for the 
56array.*/
57
58//Example:
59/*splice(index, number of items, new items) starts at index and 
60REPLACES the number of items with the new ones.*/
61let arr = ['a', 'b', 'c', 'd', 'e', 'f'];
62
63arr.splice(2,3,'hello', 9);    //Start at index 2, replace 3 entries with 'hello' and 9.
64console.log(arr);
65
66//[ 'a', 'b', 'hello', 9, 'f' ]