Splice and Slice array methods in JavaScript
Today we will discuss about the Splice and Slice array methods in JavaScript with example. splice() and slice() both methods look similar, but act in very different ways.
Splice and Slice array methods in JavaScript, JavaScript Array splice vs slice, JavaScript Array.splice() vs Array.slice(), JavaScript Array splice() Method, JavaScript Array slice() Method, splice( ), & split( ) methods in JavaScript, Array slice vs splice in JavaScript, Array.prototype.slice(), Array.prototype.splice(), javascript array methods, The slice Method for JavaScript Arrays, How to use splice and slice methods in javascript.
Checkout more articles on JavaScript
Array Methods
Method 1. splice()
The splice()
array method adds or removes items from an array and returns an array with the removed items.
Syntax of the splice()
method:
1 | array.splice(index, removeCount, itemList) |
Here, index
argument is the start index of the array from where splice()
will start removing the items. removeCount
argument is the number of elements to delete starting from index and itemList
is the list of new items which indicates the items to be added to the array.
1 2 3 4 | var colours = ["Blue","Pink","White","Yellow"]; var newArray = colours.splice(2, 2, "Black", "Purple"); console.log(colours); //Output: ["Blue", "Pink", "Black", "Purple"] console.log(newArray); // Output: ["White", "Yellow"] |
There is no need to write second argument if we want to remove all the items from starting index to end of the array.
1 2 3 4 | var colours = ["Blue","Pink","White","Yellow"]; var newArray = colours.splice(2); console.log(colours); // Output: ["Blue", "Pink"] console.log(newArray); // Output: ["White", "Yellow"] |
This method can be used when we need to add one or more items into array in place of removed items, but it’s not necessary to replace all the items we removed.
Method 2: slice()
The slice()
method returns the selected item(s) of an array into a new array. It doesn’t modify the original array.
Syntax of the slice()
method:
1 | array.slice(startIndex, endIndex); |
Here, the slice() method will select the item indexed by start argument and finish at the item indexed by end argument.
1 2 3 4 | var colours = ["Blue","Pink","White","Yellow"]; var newAray = colours.slice(0, 2); console.log(colours); //Output: ["Blue", "Pink", "Black", "Purple"] console.log(newAray); // Output: ["Blue", "Pink"] |
If you want to take any items from an array then you can use this method and it does not affect your existing array.
That’s it for today.
Thank you for reading. Happy Coding!