This content originally appeared on DEV Community and was authored by Rudra Pratap
In this article, I am writing in detail the working of slice.
slice
slice is a method on array object which is used to return a shallow array of a section of the original array.
slice accepts two parameters: start and end
By default start=0 and end=array.length, and both are optional.slice does not mutates the original array.
The start and end values can be negative too. In that case array.length is added to them.
ie if start=-2 then start is converted into start=-2+array.lengthIf the input range is not valid (for example: start > end ) then an empty array([]) is returned.
The range of the output array is [ start, end ). That is, the start index is included but not the end index.
let arr = [1,2,3,4,5]
console.log(arr.slice(2,4)) // [ 3, 4 ]
Here, the start is 2 and end is 4. Element at 2nd index is 3 and element at 4th index is 5. All the elements between the indices [2,4) will be included ie [3,4].
let arr = [1,2,3,4,5]
console.log(arr.slice(2)) // [ 3, 4, 5 ]
Here, the end parameter is not specified, therefore its default value will be used ie array.length which is 5, as a result the resulting array will contain all the elements between the indices [2,5). Therefore the result is [3,4,5]
Some more examples to grasp the concept
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"]
console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]
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"]
console.log(animals.slice(-1));
// Expected output: Array ["elephant"]
This content originally appeared on DEV Community and was authored by Rudra Pratap
Rudra Pratap | Sciencx (2023-05-04T12:54:14+00:00) slice(). Retrieved from https://www.scien.cx/2023/05/04/slice/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.