The Array.Slice() and Array.Splice() are methods of the Array class, to manipulate arrays. Although they sound similar, these two methods work differently. Let us see an example which demonstrates how the two methods are different from each other
Slice() - Creates a new array from elements of an existing array. It does not modify the original array. The Slice() method takes two arguments. The first argument is an integer that specifies where to start the selection. The second argument is optional and is an integer that specifies where to end the selection.
In the code shown above, slice() starts at position 1 and copies “two”, “three” into the new array (newArrSlice). The original array (nums) is not modified by the slice() method.
Some important points about slice():
- Index starts from zero
- If a single argument is given to the slice() method, the array returned will contain all elements from the start position to the end of array.
- If a negative value is supplied for either parameters, this means that the slice() will count the position from the end of the array, instead of the beginning. So in the above example, if we specify nums.splice(-1,-3), it will return “three” and “four”
Splice() – Deletes and/or inserts elements in an array. Unlike slice(), the splice() method modifies the original array and returns a new array. The Splice() method takes three arguments. The first parameter is the index to start deleting and/or insert elements, the second param is number of elements to remove and third param (optional) is the new elements to be added to the array.
In the code shown above, the splice() method starts at position 2 i.e element “three” and removes a length of 2 elements i.e. removes element “three” and “four”.
Some important points about splice():
- Index starts from zero
- If a single argument is given to the splice() method, all elements from the start index to the end of the array will be removed
- If a negative value is supplied for the parameter, the elements are spliced from the end and not from the beginning of the array
good example thanks :)
ReplyDelete