Javascript Array - splice method method


The splice method is a versatile way to reduce contiguous area of the Array. Additionally, it returns the removed elements in another array. So at the end of the operation, you have two arrays - the orginal array with a part of it removed and a returned array that consists of the removed items.
If you specify no argument to the splice method, it does not really do anything. It will leave the original array intact and will return an empty array.

x=[1,2,3,4,5,6,7,8,9,10];
y= x.splice();
document.writeln(x);  // outputs: 1,2,3,4,5,6,7,8,9,10
document.writeln(yy); // outputs undefined


This does not really do anything meaningful. We will rarely use splice method withut any argument. If you specify one argument to the splice method, it cuts the array after a number of element specified by that argument.
Take a look at the following example


<html>
<body>

<script type="text/javascript">
var x = [1,2,3,4,5,6,7,8,9,10];
var y= [];
y = x.splice(4);
document.writeln(x + '<br />');  // outputs: 1,2,3,4
document.writeln(y); // outputs 5,6,7,8,9,10 
</script>

</body>
</html>



Try this example online here .


If you specify two arguments to the splice method, then the second argument specifies the number of elements to remove. Take a look at the following example


<html>
<body>

<script type="text/javascript">
var x = [1,2,3,4,5,6,7,8,9,10];
var y= [];
y = x.splice(4,2);
document.writeln(x + '<br />');  // outputs: 1,2,3,4,7,8,9,10
document.writeln(y); // outputs 5,6 
</script>

</body>
</html>



Try this example online here .


What if you wish to insert some elememts in the array after splicing it, from the position of splice. Well splice method allows it. After the first and the second argument, you can add any number of arguments that will indicate the elements to be inserted.
Take a look at the following example


<html>
<body>

<script type="text/javascript">
var x = [1,2,3,4,5,6,7,8,9,10];
var y= [];
y = x.splice(4,2,101,102,103);
document.writeln(x + '<br />');  // outputs: 1,2,3,4,101,102,103,7,8,9,10
document.writeln(y); // outputs 5,6 
</script>

</body>
</html>



Try this example online here .


At this point we are formally ready to understand the definition of the splice method as.
br />
array.splice(index,howmany,item1,.....,itemX);

Where
  
Index 	- Integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array.<
howmany 	 - The number of items to be removed. If set to 0, no items will be removed
item1, ..., itemX  	-  The new item(s) to be inserted into the array