;

Javascript Array - copyWithin() Method


Tutorialsrack 27/08/2022 Jquery Javascript

In this article, you’ll learn about Javascript built-in Array.copyWithin() method. How does this method work in javascript? 

Array.prototype.copyWithin()

The Array.prototype.copyWithin() is used to shallow copies part of an array to another location in the same array and return it without modifying its length.

Syntax
array.copyWithin(target, copy_start, copy_end)

This method takes 3 parameters such as: 

Parameters

target: target is the index to which to copy the sequence. If the target parameter value is negative, the target will be counted from the end. If the parameter value is at or greater than arr.length, nothing will be copied. If the parameter is positioned after the start, the copied sequence will be trimmed to fit arr.length.

copy_start(Optional): Position where the copy of the element will start. If negative, the start will be counted from the end. By default, it is 0.

copy_end( Optional): Position where the copy of the element will start but does not include the ending element itself. If the copy_end value is negative, the end will be counted from the end. By default, it is array.length-1.

Here are some examples of copyWithin() methods:

Examples
/*
In this example we pass negative value,
this means it start with end
*/
console.log([1, 2, 3, 4, 5].copyWithin(-2));
//output => [1, 2, 3, 1, 2]
 
/*
In this example, we pass target index with Copy_start index,
*/
console.log([1, 2, 3, 4, 5].copyWithin(0, 3));
//output => [4, 5, 3, 4, 5]
 
/*
In this example, we pass target index with Copy_start index and Copy_end Index,
*/
console.log([1, 2, 3, 4, 5].copyWithin(0, 3, 4));
//output => [4, 2, 3, 4, 5]
 
/*
In this example, we pass negative target index with
negative Copy_start index and negative Copy_end Index,
*/
console.log([1, 2, 3, 4, 5].copyWithin(-2, -3, -1));
//output => [1, 2, 3, 3, 4]
 
/*
In this example, we pass target index '0' with
Copy_start index '3' and we defined the array of size '5' and
with single element at position 3 like (3:1),
3:1 where 3 is index of array and 1 is element
*/
console.log([].copyWithin.call({length: 5, 3: 1}, 0, 3));
//output => {0: 1, 3: 1, length: 5}
 
 
// ES2015 Typed Arrays are subclasses of Array
var i32a = new Int32Array([1, 2, 3, 4, 5]);
 
console.log(i32a.copyWithin(0, 2));
// Int32Array [3, 4, 5, 4, 5]
 
// On platforms that are not yet ES2015 compliant:
console.log([].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4));
// Int32Array [4, 2, 3, 4, 5]

I hope this article will help you to understand Javascript built-in Array.copyWithin() method. How does this method work in javascript? 

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags