The slice() method is employed to get some distinct factors of an array from a provided setting up index to the specified ending index.
Syntax of slice() strategy
The slice strategy usually takes two arguments as a parameter and supplies the sliced array. The syntax of writing a slice() operate is provided down below:
- The slice() system does not have an impact on the original array and returns a new sliced array.
- The last component of the presented vary of the indices is not provided in the resulting array.
Let us try out to slice a pair of arrays to recognize the slice() purpose far better.
Observe: We will use the browser console to reveal examples carried out in this submit. To open up up the browser console:
- Use the F12 key in Chrome and other chromium-primarily based browsers.
- Use CTRL + Shift + K keyboard shortcut keys for Mozilla.
- Use Option + ⌘ + C keyboard shortcut keys in Safari (if the developer menu does not surface, open Preferences by urgent ⌘ + , and in the State-of-the-art tab, look at “Show Produce menu in menu bar”).
Suppose we have an array of distinct programming languages:
We want to get the title of the languages from the next index to the fifth index. The syntax for having such a final result would go like this:
var slicedArr = arr.slice(2,5)
Now, if we console the slicedArr:
You can see that we have obtained a few things from the second index to the fifth index.
- The array index starts from zero
- The fifth element, the last ingredient in the variety of indices, is not integrated in the ensuing array, as talked about before.
How to slice from the close of the array
We can also extract elements from the stop of the array by supplying the damaging values to the slice purpose.
Unfavorable zero(-) will be deemed the very last component of the array, negative a person(-1) will be deemed the second final component of the array, and so on.
For illustration, we have an array of programming languages:
We want to get the aspects from the fourth last index to the 2nd very last index. The slice() function for finding these kinds of a end result will go like this:
var slicedArr = arr.slice(–4,-1)
To confirm, console the slicedArr:
We have acquired the actual outcome as we expected. So this is how we can use damaging values to extract elements from the close of the array.
We uncovered how to use the slice() strategy to get a subset of components from an array in this how-to guide.