How to Copy Array in JavaScript

Web developers commonly use JavaScript arrays to store different types of data. Often they need to clone the data present in one array to another, or create a copy of an array. There are plenty of ways to easily copy array in JavaScript. In this article, we will learn how to clone JavaScript arrays.

Why Copy Array in JavaScript

The most common reason why developers clone arrays is to perform tasks on its copy without modifying the original array. For example, if you want to process an array in a function without modifying the original array, then you can pass it as an argument to the function. Secondly, if you want to retain the original array for future reference, then you can create its copy and work with it.

How to Copy Array in JavaScript

Here are some of the popular ways to copy array in JavaScript. Before we proceed further, it is good to know that there are two types of copying/cloning in JavaScript – deep copy and shallow copy. In deep copy, a new array is created and copies of all the items of original array are newly created, including nested objects and function references. In this case, the cloned array and original array are completely independent of each other.

On the other hand, in shallow copy, only the top level items are copied, whereas nested objects and function references in cloned array continue to point to the original array’s items. In this case, if you modify the nested objects and function references in cloned array, then it will also modify those items in original array. If your array contains only primary data types like numbers and strings, then both deep copy and shallow copy will be the same.

1. Using slice() method

slice() method returns a copy of a subset of an array, without changing original array. It is a built-in method available for every array. Here is its syntax.

array.slice(start, end)

In the above command, you need to specify the start and end position of the items to be extracted and returned. They are both optional and can be omitted. If you do not specify them, then slice() method will return a copy of the entire array. Here is an example to demonstrate it.

var a = [1, 2, 3];
b=a.slice();
console.log(b); // output is [1, 2, 3]

Please note, the new array will be a shallow copy of original array. If you have basic data types like numbers and strings, then their clones will be present in new array. If you have references to functions and other complex data types, then they will continue to refer to the original array.

2. Using Spread Operator

Using Spread operator is another simple way to clone a JavaScript array. It basically unpacks an array into its individual items and copies them into another array. Here is its syntax.

new_array = [...old_array]

Here is an example to illustrate it.

var a = [1, 2, 3];
b=[...a];
console.log(b); // output is [1, 2, 3]

This method also creates a shallow copy of the array.

3. Using concat() method

JavaScript provides concat() method to concatenate two or more arrays. While concatenating arrays, it creates a copy to store the result of concatenated arrays. So it can also be used to copy an array. You can do this by concatenating the array you want to copy with an empty array, as shown.

var a = [1, 2, 3];
b=[].concat(a);
console.log(b); // output is [1, 2, 3]

This method also creates shallow copy of an array.

4. Using map() method

Map() method allows you to apply a specific function to all items in an array. You can also use it to clone an array. Here is an example to demonstrate it.

var a = [1, 2, 3];
b=a.map(x=>x);
console.log(b); // output is [1, 2, 3]

In our map() function, we simply specify an operation to copy each item from old array to new array.

5. Using from() method

You can also use from() function to copy an array. It allows you to create a new array from an existing array, allowing you to optionally provide a mapping function. Here is an example.

var a = [1, 2, 3];
b=Array.from(a);
console.log(b); // output is [1, 2, 3]

In above code, you simply call from() function from global Array JS object. Here is an example to use from function with map. Here you can customize the kind of mapping that happens. You can even modify the items before copying them into a new array.

var a = [1, 2, 3];
b=Array.from(a, x => x);
console.log(b); // output is [1, 2, 3]

6. Using JSON object

So far, all the above methods only provide a shallow copy of an array. This works in most of the cases, unless you have references in your arrays. In such cases, you need do to a deep copy, where even the references are created afresh before copying them into a new array. For this purpose, you can use JSON module available in every web browser. Here is an example.

var a = [1, 2, 3];
b=JSON.parse(JSON.stringify(a));
console.log(b); // output is [1, 2, 3]

In the above code, JSON.stringify() function first creates a JSON string using the original array’s copy. Then JSON.parse() function converts this JSON string into a JS array. In this case, the new array has same data as original array but is completely independent from the original array. If you make any changes to the new array, it will not modify the original array.

7. Using of() method

Array object also supports of() function that allows you to quickly copy an array. It will return the input argument wrapped in an array.

var a = [1, 2, 3];
b=Array.of(a);
console.log(b); // output is [[1, 2, 3]]

You will see that if you call of() function directly on the original array, the result will be [ [1, 2, 3] ] and not [1, 2, 3]. So you need to use the original array along with spread operator, so that it is unwrapped and only its items are supplied to of() function.

var a = [1, 2, 3];
b=Array.of(...a);
console.log(b); // output is [1, 2, 3]

8. Using assign() method

JavaScript also provides Object that provides many useful functions to work with all kinds of JS objects. You can also use it to clone an array. It copies all properties from original array to a new empty array.

var a = [1, 2, 3];
b=Object.assign([], a);
console.log(b); // output is [1, 2, 3]

Conclusion

In this article, we have learnt how to copy an array in JavaScript. If you want to do a deep copy of an array, you need to use JSON.stringify and JSON.parse as shown in solution #6. If you want to do a shallow copy, then you can use any of the other solutions. Among them, using slice method or spread operator offer simplest and fastest ways to clone an array in JavaScript.

Also read:

How to Empty Array in JavaScript
How to Merge Two JavaScript Objects
How to Check if Key Exists in JavaScript Object

Leave a Reply

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