Array slice
Using .slice()
Here is an example of using slice.
js
const books = [
'Things Fall Apart',
'Beloved',
'One Hundred Years of Solitude',
'The God of Small Things',
'Persepolis'
]
console.log(books.slice(1, 4))
console
[
'Beloved',
'One Hundred Years of Solitude',
'The God of Small Things'
]
TIP
When using .slice(a, b)
, the item at index a
is included, but the item at index b
is not.
With one argument
If slice is called with one argument, it slices to the end of the array.
js
const books = [
'Things Fall Apart',
'Beloved',
'One Hundred Years of Solitude',
'The God of Small Things',
'Persepolis'
]
console.log(books.slice(2))
console
[
'One Hundred Years of Solitude',
'The God of Small Things',
'Persepolis'
]
Negative indices
If we pass a negative index, the indices count from the end of the array, with -1
representing the index of the final item.
js
const books = [
'Things Fall Apart',
'Beloved',
'One Hundred Years of Solitude',
'The God of Small Things',
'Persepolis'
]
console.log(books.slice(-2))
console
[ 'The God of Small Things', 'Persepolis' ]