How to Copy an Array in JavaScript

In this tute, we will discuss how to copy an array in javascript. Before we get into the main topic, let me tell you about the array in brief.

An array is a special variable that can contain more than one value. These values or elements of an array can be the same or different data types. Few examples of arrays are,

// Arrays with same type of elements
var arr1 = [1, 3, 4];
var arr2 = ['a', '3', 'foo'];
var arr3 = [1.3, 10.45];

// Array with different types of elements
var arr4 = [1, 'abc', 55.99];

Copy an array in Javascript:

Now, let’s move onto copying arrays. To begin with, there two ways to copy an array in javascript:

  1. Copy by reference (Cloning).
  2. Copy by value.

Let’s see both the cases with apt examples here.

Copy by Reference or Cloning:

This method of copying makes the duplicate array to point to the original array. In simple words, if arr1 is cloned to arr2, then any change in arr2 would affect arr1 and vice versa.

Syntax:

var array1 = [...];    // list of values
var array2 = array1;   // array1 is cloned

Example:

var arr1 = [2, 3, 4];
var arr2 = arr1;        // arr1 = [2, 3, 4]
                        // arr2 = [2, 3, 4]

arr1[0] = 1;            // arr1 = [1, 3, 4]
                        // arr2 = [1, 3, 4]

arr2[1] = 2;            // arr1 = [1, 2, 4]
                        // arr2 = [1, 2, 4]

Copy By value:

Copying array by value makes a copy of the array. But unlike cloning, changes in one array does not affect the other.

Here are two ways to copy an array by value:

Method 1:

var arr1 = [10, 45, 99];
var arr2 = arr1.slice();

The slice() method slices out a subarray from the original array, that is, it creates a new array out of the original array. When it is used without parameters, it creates a copy of the entire array. This method can be used to slice a particular subarray as well by passing the start and end indices.

Method 2:

var arr1 = [45, 99, 55];
var arr2 = [];

for(var x in arr1) {
    arr2.push(arr1[x]);
}

The push() method pushes or appends the element at the end of the array. The Array forEach() can also be used here to iterate through the elements of arr1.

Let’s see what happens differently when we copy an array by value.

Example 1:

var arr1 = [10, 45, 99]
var arr2 = arr1.slice()  // arr1 = [10, 45, 99]
                         // arr2 = [10, 45, 99]

arr1[2] = 55             // arr1 = [10, 45, 55]
                         // arr2 = [10, 45, 99]

arr2[0] = 17             // arr1 = [10, 45, 55]
                         // arr2 = [17, 45, 99]

Example 2:

var arr1 = ['car', 'bike', 'truck'];
var arr2 = [];                      // arr1 = ['car', 'bike', 'truck']
                                    // arr2 = []

for(var x in arr1) {
    arr2.push(arr1[x]);
}
                                    // arr1 = ['car', 'bike', 'truck']
                                    // arr2 = ['car', 'bike', 'truck']

arr1[0] = 'cycle';                  // arr1 = ['cycle', 'bike', 'truck']
                                    // arr2 = ['car', 'bike', 'truck']

arr2[2] = 'rocket';                 // arr1 = ['cycle', 'bike', 'truck']
                                    // arr2 = ['car', 'bike', 'rocket']

Finally, If you have any queries or doubts related to copying arrays in JavaScript, just comment in the comment box provided below.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *