The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
The syntax of Array.slice() method is:
slice(start?: number, end?: number): T[]
This slice() method of Array returns a section of an array.
Parameter | Optional/Required | Description |
---|---|---|
start | optional | Zero-based index at which to begin extraction. A negative index can be used, indicating an offset from the end of the sequence. If start is undefined, slice starts from the index 0. |
end | optional | Zero-based index before which to end extraction. slice extracts up to but not including end. A negative index can be used, indicating an offset from the end of the sequence. If end is omitted, slice extracts through the end of the sequence (arr.length). |
Array.slice() returns value of type T[]
.
The slice() method can be used to extract a portion of an array.
For example,
arr
with numeric values [1, 2, 3, 4, 5].slice(1, 3)
to extract a portion of the array.result
.result
to the console.const arr = [1, 2, 3, 4, 5];
const result = arr.slice(1, 3);
console.log(result);
[2, 3]
The slice() method can be used with a negative start index to extract a portion of an array from the end.
For example,
arr
with numeric values [1, 2, 3, 4, 5].slice(-3)
to extract the last three elements of the array.result
.result
to the console.const arr = [1, 2, 3, 4, 5];
const result = arr.slice(-3);
console.log(result);
[3, 4, 5]
The slice() method can be used without arguments to create a shallow copy of the entire array.
For example,
arr
with numeric values [1, 2, 3, 4, 5].slice()
to create a shallow copy of the array.result
.result
to the console.const arr = [1, 2, 3, 4, 5];
const result = arr.slice();
console.log(result);
[1, 2, 3, 4, 5]
In this TypeScript tutorial, we learned about slice() method of Array: the syntax and few working examples with output and detailed explanation for each example.