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




JAVASCRIPT - INSERT IN ARRAY


How to insert a new Item at the end of the Array?


Let us say, we have a Array that contains three names, Mohan, Kriti and Salim. And we want to insert a new name Mika at the end of the Array.


We can use the append() Function to achieve the above.


Example :



<html>
<body>  
<script>

	var x = ["Mohan", "Kriti", "Salim"]
	x.push("Mika")
	document.write(x)  
    
</script>      
</body>
</html>


Output :



  Mohan,Kriti,Salim,Mika

So, in the above code we have created a Array and initialised to the variable x.


x = ["Mohan", "Kriti", "Salim"]

Below is how the values are positioned in the Array,

java_Collections

Next, we have used the push() function to add the new name Mika at the end of the Array.


x.push("Mika")
java_Collections


And we get the below output,


Mohan,Kriti,Salim,Mika

How to insert a new Item at a particular location in an Array?


Let us say, we have a Array that contains three names, Mohan, Kriti and Salim. And we want to insert a new name Nikhil in between Mohan and Kriti.


We can achieve that using the insert() Function.


Example :



<html>
<body>  
<script>

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


Output :



  Mohan,Nikhil,Kriti,Salim

So, in the above code we have created a Array and initialised to the variable x.


x = ["Mohan", "Kriti", "Salim"]

Below is how the values are positioned in the Array,

java_Collections

Now, if we see the above diagram, Kriti resides at position/index 1. So, what we do is, just insert the new name Nikhil at the position/index 1 using the spice() Function.


And Kriti gets shifted to index/position 2,


x.splice(1, 0, "Nikhil")
java_Collections

java_Collections

And we get the below output,


Mohan,Kriti,Salim,Nikhil