Array.slice() method returns a shallow copy of a part of an array into a new Array Object.
The part is selected on the basis of the start index and the end index passed as a parameter to the slice method.
Syntax
arr.slice([start_index[, end_index]])
start_index: specifies the start index from where the array is selected for copying.
end_index: specifies the end index until where the array will be copied. The element at end_index is not selected.
Note: The original array is not modified by the slice method.
Example:
let arr = [ 0, 1, 2, 3, 4, 5 ];
arr.slice(0,3);
// [ 0, 1, 2 ]
// The element at the end_index is not selected
Let's learn about the slice method with a few more examples.
The start index is undefined
When the start_index is undefined, start_index will be taken as 0.
let arr = [0,1,2,3,4,5];
start_index = undefined;
end_index = 3
arr.slice(start_index, end_index);
// [0, 1, 2]
The start index is negative
The negative start_index will be used as an offset from the end of the original array and the element is taken as the start.
let arr = [ 0, 1, 2, 3, 4, 5 ];
start_index = -4;
end_index = 4;
arr.slice(start_index, end_index);
/* Counting 4 (the offset) from last of
the original array is the element at index 2.*/
//last element that will be selected is at index before the end index ie. at index 3 of the original array.
// output : [2, 3]
The start index is greater than the end_index
If the start_index is greater than the end_index, an empty array will be returned by the slice method.
let arr = [ 0, 1, 2, 3, 4, 5 ];
start_index = 4;
end_index = 2;
arr.slice(start_index, end_index);
// []
The end index is omitted
When the end_index is not specified, the array will be selected till the end.
let arr = [ 0, 1, 2, 3, 4, 5 ];
start_index = 4;
arr.slice(start_index);
// [4, 5]
The end index is negative
As seen for the start_index, if the end_index is negative, it will be treated as an offset from the end of the array for the last element that needs to be copied to the new array.
let arr = [ 0, 1, 2, 3, 4, 5 ];
start_index = 1;
end_index = -2;
arr.slice(start_index, end_index);
/* Counting 2 (the offset) from last of
the original array is the element at index 4.*/
//The array will be selected from the index 1.
// output : [1, 2, 3]
The end index is greater than the length of the array
When the end_index is greater than the end index of the array, the array will be selected until the last element for copying.
let arr = [ 0, 1, 2, 3, 4, 5 ];
start_index = 1;
end_index = 8;
arr.slice(start_index, end_index);
//[1, 2, 3, 4, 5]
This article was first published on hackinbits.com
Top comments (1)
Great choice on the header image.