Slice is a helpful tool that can be called on Arrays
that takes your initial array and gives you a slice of the original array. The new sliced array is a shallow copy of the original, so it doesn't mutate the initial array.
const data = [1,2,3,4,5] const sliced = data.slice(2) console.log(sliced) // sliced : [3,4,5]
Console:
In this first example, we have an array of numbers 1-5. We then call .slice on the original array, and pass a 2 as the first argument to slice. This first argument tells slice what index to start our new sub array from, and since we didn't pass a second argument, the new sliced array takes all items from the start index to the end of the array.
const data = [1,2,3,4,5]; const sliced = data.slice(2,3); console.log(sliced) // sliced : [3]
Console:
In this example, we pass in the second argument which tells the slice method where to stop slicing our new array. This end index acts a bit weird though. Instead of the end index pointing to the last item in our new array, it instead tells slice to select up to but not include the end index.
const data = [1,2,3,4,5]; const sliced = data.slice(2,4); console.log(sliced) // sliced: [3,4]
Console:
const data = [1,2,3,4,5]; const sliced = data.slice(2,5); console.log(sliced) // sliced: [3,4,5]
Console:
Hopefully that helped clear up the use of the array slice method. Now get out there and start slicing up arrays!