Sometimes, we may want to get a subarray from a JavaScript array.
In this article, we’ll look at how to get a subarray from a JavaScript array.
Array.prototype.slice
The JavaScript array’s slice instance method takes the beginning and ending index of the array that we want to extract.
The end index is excluded.
It returns an array with the items starting from the beginning index and the end index minus 1.
For instance, we can write:
const arr = [1, 2, 3, 4, 5];
const sub = arr.slice(1, 3)
console.log(sub)
Then sub is [2, 3] since we extract the array from index 1 to 2 and return it.
We can also pass in negative indexes to the slice method.
Negative indexes mean we start counting from the end of the array instead of the start.
So -1 is the last element of the array, -2 is the 2nd last one, and so on.
So we can replace the code above with:
const arr = [1, 2, 3, 4, 5];
const sub = arr.slice(1, -2)
console.log(sub)
and get the same value for sub .
Conclusion
We can use the JavaScript array’s slice method to extract a subarray from a JavaScript array.