Author : Jay

Published on: April 5, 2016

Category : Technical Feed

Recently, during one of the local JavaScript weekend workshops, one of the guys raised a question about JavaScript Array.prototype.splice(). He showed the below sample code:

var a = [‘apple’,’boy’,’cat’];
var b = a.splice(0,2);
console.log(a); // outputs [‘cat’]
console.log(b); // outputs [‘apple’.’boy’]

The question was quite simple, he asked “Why is JavaScript Splice() method called so, even though it splits the array into two.” From the point of view of someone who has used splice to only split arrays, the question is quite a legit one. But one thing that he didn’t knew or forgot was that splice can remove as well as add elements from an array and that too at the same time. JavaScript splice if used to add and remove elements at the same time, takes in 3 arguments and this process of removing and adding elements is called splicing.

Introduction

The word Splice means to join or combine two ends of a rope, string etc by interweaving strands at the end. JavaScript Array.splice() does the same job of combining two ends of an array. The Array.splice() method is used to change the contents of an array. Using splice() we can specify the index to begin removing items, and the number of items to remove. In the same function call, we can also specify new items to add to the array. The syntax of splice() is shown below.

array.splice(index , howMany[, element1[,[, elementN]]])

splice() takes a variable number of arguments. The first argument, which is required, represents the index at which the array manipulation will begin. If this index is negative, then it is interpreted as an offset from the end of the array. The second argument, howMany, is also required, and is used to specify the number of elements to remove from the array. Finally, you can specify any number of additional optional arguments which represent items to be added to the array. splice() returns an array of removed items. If no items are removed, an empty array is returned.

Adding and Removing Elements from JavaScript Array

Array.prototype.push()

First method that we are going to discuss is push/pop. Push is a method for adding elements to the end of a JavaScript array. Push method appends elements to an array and returns the number of elements in the array. Syntax for push is shown below:

var guest = [‘Ravi’, ‘Hari’, ‘John’, ‘Sam’];
var t = guest.push(Jay’, ‘Simi);
console .log(JSON.stringify(guest));

Here is the output of the above code:

[code][‘Ravi’, ‘Hari’, ‘John’, ‘Sam’, ‘Jay’, ‘Simi’][/code]

Push always inserts elements only to the end of an array. It’s not possible to insert an element in the middle of an array using push.

Array.prototype.pop()

Pop is the better half of push. Push inserts an element to the end of an array and pop removes an element from the end of an array. It simply removes the last element and returns it. Syntax for pop is:

array.pop()

Here is sample example which shows pop in action.

var removedElement = guest.pop();
console.log(‘Removed element is ‘, removedElement);

Array.prototype.shift()

Shift removes the first element from the beginning of the array and returns it back. Syntax for shift is as shown below:

array.shift()

Here is an example for shift:

guest.shift();
console.log(‘Guest list after removing first element: ‘, JSON.stringify(guest))

Here is the output of the above code:

[code]Guest list after removing first element: [‘Jennifer’, ‘Ravi’, ‘Hari’, ‘John’, ‘Sam’][/code]

Here is a demo of the shift/unshift methods.

Array.prototype.splice()

The JavaScript methods that we discussed above, are either useful for adding/removing elements from the beginning or from the end of an array. But, what if we need to add/remove an element from the middle of an array or from any other particular index point. That is where Array.prototype.splice() comes into the picture.
Below is the syntax for splice

[code]array.splice(index , howMany[, element1[, ...[, elementN]]])[/code]

When trying to add an element or multiple elements to an array, we need to specify the index from which to add the elements, number of elements to be removed if any and the new elements to be added if any. Consider an array as shown below:

[code]var categories = ['JavaScript', 'C#', 'Python', 'Java', 'HTML'][/code]

Suppose, we want to empty the whole array using splice. In order to accomplish that, simply specify the index value as 0. Second argument if left blank, would remove all elements after the index and third argument if left blank, will only remove elements from the array. So, the below code would empty the whole array:

[code]categories.splice(0); // empties the whole array[/code]

Similarly, specifying the second argument along with the first, we can remove particular number of elements from the array. In order to remove second element from the array, use splice as shown below:

[code]categories.splice(1,1); //removes C# from the array[/code]

Now, suppose we want to add another element Scala, here is how we do that:

[code]categories.splice(0,0,'Scala');[/code]

In the above code, we removed zero elements from index 0 and added an element called Scala. The above code adds the new element to front of the array.
Here is the output array:

Category List after adding Scala : [‘Scala’, ‘C#’, ‘Python’, ‘Java’, ‘HTML’]

Similarly, it’s possible to add elements anywhere in the array by specifying the particular index as first argument in splice. Specifying a negative index to the splice() can be used to traverse the array in reverse direction. So in order to add an element to the second last position of an array we need to specify index as -1 and elements will be added to the second last position. Here is a sample:

[code]categories.splice(-1, 0, 'Ruby');[/code]

Here is the output of the above code:

[code]Category List after adding Ruby: ['Scala', 'C#', 'Python', 'Java', 'Ruby', 'HTML'][/code]

Similarly, in order to add an element to last position simply set index as (length of the array) or a number greater than the length of the array. Let’s add an element to end of an array:

[code]categories.splice(categories.length, 0, 'Objective C');[/code]

Here is the output array:

[‘Scala’, ‘C#’, ‘Python’, ‘Java’, ‘Ruby’, ‘HTML’, ‘Objective C’]

Here is a demo of the above code.

Apart from adding and removing elements of an array, sometimes it’s required to

replace a particular element of an array. Replacing an element can also be accomplished using splice(). Replacing an element using splice() is actually a combination of removing and adding element. Suppose, we need to replace the JavaScript element with another new element called Perl. Here is how it is accomplished:

var categories = [‘JavaScript’, ‘C#’, ‘Python‘, ‘Java’, ‘HTML’];
console.log(‘Category list before removal is ‘, JSON.stringify(categories));
var removedCategories = categories.splice(0,1,’Perl’);
console.log(‘Removed categories are ‘, JSON.stringify(removedCategories));
console.log(‘Category list after removal is ‘, JSON.stringify(categories));

In order to replace the element, we set the index to remove as 0 and number of element to remove as 1 to remove JavaScript element and specified a new element called Perl to be added at its place. Here is the output of the above code:

[code]Category list before removal is[‘JavaScript’, ‘C#’, ‘Python’, ‘Java’, ‘HTML’]
Removed categories are[‘JavaScript’]
Category list after removal is[‘Perl’, ‘C#’, ‘Python’, ‘Java’, ‘HTML’]
[/code]

Now, suppose if we want to replace JavaScript element with multiple elements. We simply need to pass mutiple elements as shown below:

categories.splice(0,1,‘Perl’,‘Haskel’);

Here is a demo of the replacing elements using splice in action.

Wrapping it up

In this article, we saw how Array.splice() method helps to change the contents of an array by adding and removing elements. We discussed about push/pop and unshift/shift which helps in adding/removing elements from the end of the array and from the beginning of the array respectively and also how Array.splice helps in adding/removing elements at any index of the array. Official documentation for Splice can be found here.

FacebooktwitterlinkedinFacebooktwitterlinkedin

Tags: