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




copyWithin() - FUNCTION


copyWithin() Function is used to copy array elements and place it in some other location.


Let us say, we have a Array that contains five names, Mohan, Kriti, Philip, Salim and Andrew. And we want to take the name Mohan and Kriti and replace them with Philip and Salim.


In other words, Philip and Salim would be replaced by Mohan and Kriti.

java_Collections

Example :



<html>
<body>  
<script>

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


Output :



  Mohan,Kriti,Mohan,Kriti,Andrew

So, we have an Array that has 5 names.

java_Collections

So, all we have done is, used the copyWithin() method to copy the elements at index 0 till index 1(The end index represents length i.e. 1+1) and copy them to index 2.


x.copyWithin(2, 0, 2)
java_Collections


And we get the below Array.

java_Collections

Let us see the next example, where we want to copy Kriti and replace with Salim.

java_Collections

So, Kriti is at index 1(Should be the start index) and it has to be placed at index 3(Where Salim resides). And only Kriti has to be copied, so we can give the end index as 1+1 i.e. 2.


x.copyWithin(3, 1, 2)

Let us write the code for it.


Example :



<html>
<body>  
<script>

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


Output :



  Mohan,Kriti,Philip,Kriti,Andrew

And as we can see, Salim is replaced with Kriti.