slice
slice (pure)
Given a start and an end index, creates a sub-array from the array passed as a parameter.
The element at the end index will not be included. Also, all parameters are optional: the start index defaults to 0, and the end index defaults to the array length.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
// You can also use negative numbers, that represent the indexes
// starting from the end of the array
console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]
console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
Backlinks