Extracting Part of an Array
Extracting part of an Array: slice()
The slice()
method in JavaScript extracts a section of an array and returns it as a new array without modifying the original array. This method is helpful when working with a portion of an array without affecting the original one.
The slice()
function takes two arguments: the start index (inclusive) and the end index (exclusive). The range defined by these indices is used to select elements from the array.
Examples
Example 1, using slice()
to extract a subarray:
In this example:
- The start index is
1
(which is βcatβ), and the end index is4
(which is βlionβ, but since the end index is exclusive, itβs not included). - The extracted subarray includes the elements from index
1
to3
.
Example 2, using slice()
with only the start index:
- In this case, by providing only the start index (2),
slice()
extracts all elements from index 2 to the end of the array.
Example 3, using slice()
with negative indices:
- Negative indices can be used with
slice()
. A negative start index counts from the end of the array, so-2
refers to the second-to-last element, and the extraction continues to the end.
Notes
- Non-destructive: The
slice()
method does not modify the original array. - Empty array: If the start index is greater than or equal to the array length, or if the start index is greater than the end index,
slice()
returns an empty array. - Omitting arguments: If both start and end are omitted,
slice()
returns a shallow copy of the entire array. - The
slice()
method returns a shallow copy of a portion of an array into a new array object. - The
slice()
method can take no arguments: the start index is 0 and the end index is the length of the array.