Javascript
Arrays
Written by:
Cloning an Array in JavaScript is a very common operation in various scenarios. In this article, we will learn how to clone an Array and some cases in which this technique can be used. Here is a short example of how to clone an Array in JavaScript:
1let originalArray = [1, 2, 3, 4, 5]; 2let arrayCloned = [...originalArray]; 3 4originalArray = ["Hello", "World!"]; 5 6console.log(originalArray); // output: [ 'Hello', 'World!' ] 7console.log(arrayCloned); // output: [ 1, 2, 3, 4, 5 ]
In this example, we used the spread operator (...arrayName
) to create a shallow copy of the originalArray
, this will create a new Array arrayCloned
with the same elements. If after cloning the Array you want to change the values of the original Array this will not affect the values of the Array we just cloned because those values point to a different space in the system memory.
Cloning an Array means creating a new Array that has the same elements as the original Array, but that is a different object in memory. This way if you modify the original Array it will not affect the cloned Array and vice versa. In JavaScript, Arrays are referenced types, so without proper cloning, modifying an Array may unintentionally affect other parts of the code.
Possibly the best way to easily clone an Array in JavaScript is by using the spread operator, it creates a new Array containing the same values as the original Array but with a different space in memory as shown in the following example:
1let originalArray = [1, 2, 3, 4, 5]; 2let clonedArray = [...originalArray]; 3 4console.log(originalArray); // output: [ 1, 2, 3, 4, 5 ] 5console.log(clonedArray); // output: [ 1, 2, 3, 4, 5 ] 6 7originalArray = ["A", "B", "C", "D", "E"]; 8 9console.log(originalArray); // output: [ 'A', 'B', 'C', 'D', 'E' ] 10console.log(clonedArray); // output: [ 1, 2, 3, 4, 5 ]
Here we clone the Array originalArray
using the spread operator, this creates a new Array clonedArray
with the same values as the original Array but with a different space in memory.
Another very useful way that allows you to clone an Array in JavaScript is the Array.from()
method, which takes an Array or an iterable object and returns a new Array.
1let originalArray = ["Apple", "Banana", "Watermelon", "Orange", "Strawberry"]; 2let clonedArray = Array.from(originalArray); 3 4originalArray = ["A", "B", "C", "D", "E"]; 5 6console.log(originalArray); // output: [ 'A', 'B', 'C', 'D', 'E' ] 7console.log(clonedArray); // output: [ 'Apple', 'Banana', 'Watermelon', 'Orange', 'Strawberry' ]
The Array.from()
method creates a clone of the original Array in a similar way as the spread operator does, this method receives an Array or an iterable object and returns an Array with the same values.
The concat()
method can also be used to clone an Array in JavaScript.
1let originalArray = ["Apple", "Windows", "Linux"]; 2let clonedArray = [].concat(originalArray); 3 4originalArray = [3, 1, 4]; 5 6console.log(originalArray); // output: [ 3, 1, 4 ] 7console.log(clonedArray); // output: [ 'Apple', 'Windows', 'Linux' ]
The concat()
method concatenates two Arrays and returns a new one, concatenating an empty Array with the original Array creates a copy of the original Array that can be stored in a new variable.
Another method you can use to create a copy of an Array in JavaScript is the slice method, below is an example of how to do it:
1let originalArray = ["OpenAI", "Google", "Microsoft"]; 2let clonedArray = originalArray.slice(); 3 4originalArray = [2, 9, 9]; 5 6console.log(originalArray); // output: [ 2, 9, 9 ] 7console.log(clonedArray); // output: [ 'OpenAI', 'Google', 'Microsoft' ]
The slice()
method is a method that returns a copy of a portion of the original Array. This method receives two parameters, the first represents the index at which the method will start slicing the Array and the second parameter represents the index at which it will end. But if no parameter is specified, it will copy the entire original Array and return a copy with the same values.
All of the examples above create a shallow copy of an Array. If you need to make a deep copy of an Array a good option may be to use the JSON.parse(JSON.stringify(originalArray)
syntax.
1const originalArrayOne = [1, 2, 3, 4, 5, { name: "Thomas" }]; 2const originalArrayTwo = ["a", "b", "c", { name: "Andrew" }]; 3 4const shallowClone = [...originalArrayOne]; 5const deepClone = JSON.parse(JSON.stringify(originalArrayTwo)); 6 7// We are modifying it so you can notice how it doesn't change the original Array. 8shallowClone[0] = "X"; 9shallowClone[5].name = "Jane"; 10 11deepClone[0] = 20; 12deepClone[3].name = "John"; 13 14console.log("Shallow clone"); 15console.log(originalArrayOne); // output: [ 1, 2, 3, 4, 5, { name: 'Jane' } ] 16console.log(shallowClone); // output: [ 'X', 2, 3, 4, 5, { name: 'Jane' } ] 17 18console.log("\nDeep clone"); 19console.log(originalArrayTwo); // output: [ 'a', 'b', 'c', { name: 'Andrew' } ] 20console.log(deepClone); // output: [ 20, 'b', 'c', { name: 'John' } ]
code output:
1Shallow clone 2[ 1, 2, 3, 4, 5, { name: 'Jane' } ] 3[ 'X', 2, 3, 4, 5, { name: 'Jane' } ] 4 5Deep clone 6[ 'a', 'b', 'c', { name: 'Andrew' } ] 7[ 20, 'b', 'c', { name: 'John' } ]
A shallow copy only copies the primitive values (numbers, strings, booleans, etc...), but it does not copy the objects or nested Arrays. If you want to create a deep copy of the original Array that also copies the objects or the nested Arrays, you can use the JSON.parse(JSON.stringify(originalArray)
syntax.
As shown in the example above, if you create a shallow copy of an Array using the spread operator or any of the other methods and change one of the primitive values of the cloned Array it will not affect the original Array but if you change the values of an object or a nested Array it will affect the original Array as well. This problem can be solved by making a deep copy of the Array, this way no matter what values you change in the cloned Array it will never affect the original Array and vice versa.
These are some examples, but there are many different situations in which it can be useful to clone an Array, either for security or for simplicity when analyzing or simply working with data.
Cloning an Array can be very useful in many different situations, in this article we cover some of the most common ways to clone an Array in JavaScript, a fundamental skill for efficient data manipulation. Understanding the nuances of array cloning is crucial in avoiding unintended side effects in your code. Dive deeper into JavaScript and Array manipulation by exploring more articles and resources on our blog. If you're eager to advance your skills in web development, consider signing up for free at 4Geeks.com.
¡Have fun in your software development journey! 😀👋