Javascript array slice()
method is used to slice a portion of an array which is returned as a new array. Portion that is sliced is selected based on the passed start and end.
slice() method syntax
slice(start, end)
start- Index from where extraction has to be started. Index is zero based. This parameter is optional, if not passed starting index is considered as 0.
end- Index to end the extraction. slice() extracts up to but not including end. This parameter is optional, if not passed extraction ends at the last element of the array.
Return value
A new array containing the extracted elements. Note that returned array is a shallow copy which means any change in the returned array will also reflect in original array.
Note that slice() method also works with negative indexes. Negative index counts back from the end of the array. Last element has the index of -1, second last has the index of -2 and so on. if start < 0, start + array.length is used.
slice() method example
1. Using slice() method with different start and end parameters.
const cities = ['New Delhi', 'Mumbai', 'Chennai', 'Varanasi', 'Bangalore']; //Without passing start and end let newCities = cities.slice(); console.log(newCities); //['New Delhi', 'Mumbai', 'Chennai', 'Varanasi', 'Bangalore'] // From index 1 to end newCities = cities.slice(1); console.log(newCities); //['Mumbai', 'Chennai', 'Varanasi', 'Bangalore']; //From index 1 to 3 (3 not included in the result) newCities = cities.slice(1, 3); console.log(newCities); //['Mumbai', 'Chennai']; //From index 0 to -2 newCities = cities.slice(0, -2); console.log(newCities); //['New Delhi', 'Mumbai', 'Chennai'];
Using slice() with array of objects
When you use slice() method a shallow copy of a portion of an array is created. Since it is a shallow copy so object references remain same as in original array. Let's try to understand it with an example, suppose you have an array of persons object and you slice it to get a portion of it.
const persons = [{id:1, name:"Ajay", age:9}, {id:2, name:"Rajiv", age:22}, {id:3, name:"Bosco", age:25}, {id:4, name:"Albert", age:3}]; // Getting object at index 1 let newPersons = persons.slice(1, 2); console.log(newPersons); //[{id:2, age:22, name:"Rajiv"}]
Now if you try to change object field in this new array it also reflects in the original array because of shared object reference.
newPersons[0].name = "Amit"; console.log(newPersons); // {id: 2, name: 'Amit', age: 22} console.log(persons); /* {id: 1, name: 'Ajay', age: 9}, {id: 2, name: 'Amit', age: 22}, {id: 3, name: 'Bosco', age: 25}, {id: 4, name: 'Albert', age: 3}*/
That's all for this topic JavaScript Array slice() method With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-
No comments:
Post a Comment