The following operators are valid for arrays. Note: in addition to these operators, there is a membership infix operator that works on arrays and maps, and there are also Set Operators, which are extremely useful when comparing & inspecting arrays.
...
- the zero-based index of where to start the splice
- the number of elements to remove at the location given by the first argument
- an optional value to be spliced in the array at the location given by the first argument
The following example shows elements being removed from an array:
Code Block |
---|
language | javascript |
---|
theme | Confluence |
---|
|
a = ['corn','tomato','tomato','tomato','sprouts','lettuce','sprouts'];
c = a.splice(1,4); // c = ['corn','lettuce','sprouts'] |
If the operational third argument is included it will be inserted. If the argument is an array, the elements of the array will all be inserted.
Code Block |
---|
language | javascript |
---|
theme | Confluence |
---|
|
a = ['corn','tomato','sprouts','lettuce','sprouts'];
b = ['corn','tomato'];
c = a.splice(2, 0, b); // c = ['corn','tomato','corn','tomato','sprouts','lettuce','sprouts'] |
If the third argument is not an array, its value be inserted.
Code Block |
---|
language | javascript |
---|
theme | Confluence |
---|
|
a = ['corn','tomato','sprouts','lettuce','sprouts'];
c = a.splice(2, 0, 'liver'); // c = ['corn','tomato','liver','sprouts','lettuce','sprouts'] |
In the preceding examples, we've been removing zero elements (i.e. simply inserting). If the second argument is non-zero, then that many elements will be removed before the elements of the third argument are inserted at the location where the elements were removed:
Code Block |
---|
language | javascript |
---|
theme | Confluence |
---|
|
a = ['corn','tomato','sprouts','lettuce','sprouts'];
c = a.splice(2, 2, 'liver'); // c = ['corn','tomato','liver','sprouts'] |
If the second argument is larger than the remaining elements in the array, the array will be truncated at the location given by the first parameter:
Code Block |
---|
language | javascript |
---|
theme | Confluence |
---|
|
a = ['corn','tomato','tomato','tomato','sprouts','lettuce','sprouts'];
c = a.splice(1,10); // c = ['corn'] |
sort()
The sort()
operator takes an optional argument and returns an array that is the original array sorted according to the following criteria:
...