![]() |
VOOZH | about |
Multiple methods can be used to duplicate an array in JavaScript.The fastest way to duplicate an array in JavaScript is by using the slice() Method. Let us discuss some methods and then compare the speed of execution.
The methods to copy an array are:
Table of Content
The slice() method is a built-in JavaScript method that creates a new array with the same elements as the original array. It does not modify the original array. It is considered one of the fastest methods as it directly returns a shallow copy of the original array.
arr.slice(begin, end);Example: In this example, we have used slice() method
Duplicate array is: [ 1, 2, 3, 4, 5 ]
The concat() method creates a new array by concatenating the original array with an empty array. It does not modify the original array. It is considered a bit slower than slice method as it creates a new array and concatenates it with the original array.
str.concat(string2, string3, string4,......, stringN);Example: In this example, we have used concat() method
Duplicate array is: [ 1, 2, 3, 4, 5 ]
The spread operator creates a new array with the same elements as the original array. It does not modify the original array. It is considered as fast as the slice method as it directly creates a new array with the spread of the original array.
let variablename1 = [...value]; Example: In this example, we have used Spread operator
Duplicate array is: [ 1, 2, 3, 4, 5 ]
This method creates a new array by passing the original array to JSON.stringify() method and passing the result to JSON.parse() method. It is considered one of the slowest method as it uses two methods and also it can only be used with JSON string.
JSON.parse( string, function )
JSON.stringify(value, replacer, space);
Example: In this example, we have used JSON.parse() and JSON.stringify()
Duplicate array is: [ 1, 2, 3, 4, 5 ]
JavaScript for loop is used to iterate the elements for a fixed number of times. JavaScript for loop is used if the number of the iteration is known.
for (statement 1 ; statement 2 ; statement 3){
code here...
}
Example: In this example, This duplicateArray function uses a for loop to iterate over the elements of the original array and copies them to a new array. This method is straightforward and will create a shallow copy of the array.
[ 1, 2, 3, 4, 5 ]
Conclusion: