At times, we might require to have some of the elements from the array, as another array. In such situations, we can make use of the slice method. This method slices the array into a new array.
The slice method requires some data, like the start position, and the end position and the array is sliced. This just means that the new array is going to contain the elements from the specified starting index, up to the end index (the end index element not included).
If we are not giving the end index, then the array is by default sliced from the specified start to the last element in the array. On the other hand, if the start position is not specified, the default start position is going to be 0. so, in short, giving both the arguments is optional. Also remember that this method is going to return the new array, with the required elements.
Let’s have a look at an example, which demonstrates the use of the method slice –
As you can see in the above program, we have an array, and we are calling the slice method, and we have provided the start as 1, and the end as 4. This simply means that the new array would contain the elements from index 1, to index 3, since the end is not inclusive. Let’s have a look at the output now →
As you can see. We could slice the array from the given index, to the given index. Remember that the last index that we are giving, is not included. So, we have to take care of this while we are giving some input.