Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




splice() - FUNCTION


splice() Function is used to add or remove elements from an Array.


Let us say, we have a Array that contains four names, Mohan, Kriti, Philip and Salim. And we want to remove the elements Kriti and Philip from the Array.


Removing a chunk of elements from the Array using splice() function


Example :



<html>
<body>  
<script>

	var x = ["Mohan", "Kriti", "Philip", "Salim"]
	x.splice(1,2)
	document.write(x)
    
</script>      
</body>
</html>


Output :



  Mohan,Salim

So, we have the below Array,


var x = ["Mohan", "Kriti", "Philip", "Salim"]
java_Collections


And we want to remove the elements Kriti and Philip from the Array.


x.splice(1,2)
java_Collections

java_Collections

Next, let us say, we have a Array that contains four names, Mohan, Kriti, Philip and Salim. And we want to add the name Benny in between Philip and Salim.


Adding elements to the Array at a specific location


Example :



<html>
<body>  
<script>

	var x = ["Mohan", "Kriti", "Philip", "Salim"]
	x.splice(3, 0, "Benny")
	document.write(x)
    
</script>      
</body>
</html>


Output :



  Mohan,Kriti,Philip,Benny,Salim

So, all we have done is used the splice() method to add the name Benny at index 3. And also mentioned 0. So that no elements gets removed from the array.


x.splice(3, 0, "Benny")

And what happens is Benny gets inserted at index 3 pushing Salim at index 4.

java_Collections