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




JAVASCRIPT - COPY FROM ARRAY


How to copy one Array to the other?


There are two ways by which we can copy one Array to the other.

  1. Using the method slice()

  2. Using the method concat()

Let us look at the first way using the slice() method.


Example :



<html>
<body>  
<script>

	var x = ["Mohan", "Kriti", "Salim"]
	var y = x.slice()
	document.write("The Copied Array is : [ ",y," ]")  
    
</script>      
</body>
</html>


Output :



  The Copied Array is : [ Mohan,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-Script-Copy-from-Array

Then we have used the slice() method that would create an exact copy of x. And assign it to y.


	var y = x.slice()
Java-Script-Copy-from-Array


And we get the below output,


The Copied Array is : [ Mohan,Kriti,Salim ]

Now, let us look at the second way of copying a Array using concat() method.


Example :



<html>
<body>  
<script>

	var x = ["Mohan", "Kriti", "Salim"]
	var y =  [].concat(x)
	document.write("The Copied Array is : [ ",y," ]") 
    
</script>      
</body>
</html>


Output :



  The Copied Array is : [ Mohan,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-Script-Copy-from-Array

Then we have used the concat() method to join the existing array with an empty array. And the new array y would contain the same elements as the array x.


	var y =  [].concat(x)
Java-Script-Copy-from-Array


And we get the below output,


The Copied Array is [ Mohan,Kriti,Salim ]