Copy elements within an array using JavaScript : copyWithin()

JavaScript arrays come equipped with various methods that facilitate manipulation and transformation of array elements. One such method is copyWithin(), which allows you to copy a sequence of elements within the same array, overwriting existing values. In this article, we’ll explore the copyWithin() method in depth, covering its syntax, functionality, and usage through detailed examples.

Syntax:

The syntax of the copyWithin() method is as follows:

array.copyWithin(target, start, end)

Parameters:

  • target: The index at which to copy the sequence to.
  • start: The index at which to start copying elements from.
  • end (optional): The index at which to stop copying elements (not inclusive). If omitted, copyWithin() copies until the end of the array.

Return Value:

The modified array with the copied elements.

Examples:

Let’s explore the copyWithin() method with some illustrative examples:

Example 1:

let numbers = [1, 2, 3, 4, 5];
numbers.copyWithin(0, 3);
console.log(numbers); // Output: [4, 5, 3, 4, 5]

In this example, the sequence starting from index 3 (4, 5) is copied to the beginning of the array (index 0), effectively replacing the elements at indices 0 and 1 with the copied sequence.

Example 2:

let fruits = ['apple', 'banana', 'cherry', 'date', 'fig'];
fruits.copyWithin(2, 0, 2);
console.log(fruits); // Output: ['apple', 'banana', 'apple', 'banana', 'fig']

Here, the sequence starting from index 0 and ending before index 2 (‘apple’, ‘banana’) is copied to index 2, overwriting the elements at indices 2 and 3 (‘cherry’, ‘date’).

Example 3:

let letters = ['a', 'b', 'c', 'd', 'e'];
letters.copyWithin(1, 3, 4);
console.log(letters); // Output: ['a', 'd', 'c', 'd', 'e']

In this example, the sequence starting from index 3 and ending before index 4 (‘d’) is copied to index 1, replacing the element at index 1 (‘b’).

The copyWithin() method in JavaScript provides a convenient way to copy and overwrite elements within the same array. By understanding its syntax and parameters, you can efficiently manipulate array elements according to your requirements. Experiment with different scenarios and array configurations to fully grasp the versatility of the copyWithin() method and enhance your JavaScript programming skills.

Author: user