Home » JavaScript

Array copyWithin() method with example in JavaScript

JavaScript copyWithin() method: Here, we are going to learn about the copyWithin() method of array in JavaScript.
Submitted by IncludeHelp, on March 02, 2019

JavaScript copyWithin() method

copyWithin() method is used to copy the specified elements from an array and replace from specified index within the same array. It changes the this array (actual array).

Syntax:

    array.concat(target_index, [start_index], [end_index]);

Parameters:

  • target_index is an index in the same array to replace the elements.
  • start_index is an optional parameter and it's default value is 0, it is used to specify the source start index to copy the elements.
  • end_index is also an optional parameter and it's default value is array.lentgh, it is used to specify the source end index.

Example:

    Input:
    var names = ["Manju", "Amit", "Abhi", "Radib", "Prem"];

    Function call:
    names.copyWithin(2, 0);
    
    Output:
    Manju,Amit,Manju,Amit,Abhi

JavaScript Code to demonstrate example of Array.copyWithin() method

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>
		var names = ["Manju", "Amit", "Abhi", "Radib", "Prem"];
		
		document.write("Before function call...<br>");
		document.write("names: " + names + "<br>");
		
		//copy from 0th index and replace from 2nd index
		names.copyWithin(2);
		
		document.write("After function call...<br>");
		document.write("names: " + names + "<br>");	
		
		//another example
		var arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
		
		document.write("Before function call...<br>");
		document.write("arr: " + arr + "<br>");		
		
		//copy from 1st index to 3rd and replace from 6th index
		arr.copyWithin(6,1,4);
		
		document.write("After function call...<br>");
		document.write("arr: " + arr + "<br>");				
	</script>
</body>
</html>

Output

Before function call...
names: Manju,Amit,Abhi,Radib,Prem
After function call...
names: Manju,Amit,Manju,Amit,Abhi
Before function call...
arr: 10,20,30,40,50,60,70,80,90,100
After function call...
arr: 10,20,30,40,50,60,20,30,40,100





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.