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




JAVASCRIPT - REPLACE ARRAY ELEMENTS


How to change/replace an Item in a Array?


Let us say, we have a Array that contains three names, Mohan, Kriti and Salim. And we want to replace the name Kriti with a new name Paul.


Example :



<html>
<body>  
<script>

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


Output :



  Mohan,Paul,Salim

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


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

Now, let us see, 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 replace the position/index 1 (i.e. x[1]) with the new name Paul.


x[1] = "Paul"
java_Collections


And we get the below output,


Mohan,Paul,Salim

How to change/replace an Item in a Array with another Array?


Let us take the same example, in which we have a Array that contains three names, Mohan, Kriti and Salim. And we want to replace the name Kriti with a Array with another Array that has two names, Rishav and Rishav.


Example :



<html>
<body>  
<script>

	var x = ["Mohan", "Kriti", "Salim"]
	x[1] = ["Rishav","Rishav"]
    
    for (let i =0; i<x.length; i++)
		document.write(x[i], "</br>")
    
</script>      
</body>
</html>


Output :



  Mohan
  Rishav,Rishav
  Salim

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


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

Now, let us see, 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 replace the position/index 1 (i.e. x[1]) with the new Array that has two names, Rishav and Rishav.


x[1] = ["Rishav","Rishav"]
java_Collections


And we get the below output,


Mohan
Rishav,Rishav
Salim