Slice() and Splice() in JavaScript




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.

Slice() Javascript

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.

Slice() Javascript

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.

Splice() Javascript

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”.

Splice() Javascript

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


Will you give this article a +1 ? Thanks in advance




About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "Slice() and Splice() in JavaScript"
  1. Suresh Sundar said...
    March 18, 2014 at 5:19 AM

    good example thanks :)

 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions