We have covered removing items from arrays in JavaScript, as well as checking whether an item is present in an array.
This article will look at copying or returning a subsection of arrays using the slice() method in Javascript.
slice() Syntax
arr.slice([start[, end]])
Where:
- arr is an array or existing array variable
- start is the index to start the slice at
- If it is undefined, it will default to 0
- The index is the position of the item within the array. Remember, they start at 0!
- end is the index to end the slice at
- If it is undefined, the end of the array will be used
- A new array will be returned, containing the value of the elements between and including the start and end indexes
- This is an entirely new array. Modification made to elements in it will not affect the original array
Examples of Array slice() Method in JavaScript
The below example creates a new array containing the animals with wings by extracting them from the animals array by their position:
var animals = ['Cat', 'Dog', 'Parrot', 'Pigeon', 'Flamingo', 'Elephant']; var wings = animals.slice(2, 4); // animals contains ['Cat', 'Dog', 'Parrot', 'Pigeon', 'Flamingo', 'Elephant'] // wings contains ['Parrot', 'Pigeon', 'Flamingo']
Using Negative Indexes
Negative indexes can also be supplied to work backward from the last index:
var animals = ['Cat', 'Dog', 'Parrot', 'Pigeon', 'Flamingo', 'Elephant']; var wings = animals.slice(-4, -1); // animals contains ['Cat', 'Dog', 'Parrot', 'Pigeon', 'Flamingo', 'Elephant'] // wings contains ['Parrot', 'Pigeon', 'Flamingo']
Conclusion
Getting a portion of an array is particularly useful for things like pagination – when you have a long array of data that you want to break into chunks for display.