Fastest way to duplicate an array in JavaScript
Last Updated :
16 Jan, 2024
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:
Method 1: Using slice()
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.
Syntax:
arr.slice(begin, end);
Example: In this example, we have used slice() method
JavaScript
let originalArray = [1, 2, 3, 4, 5];
let duplicateArray = originalArray.slice();
let arr = [1, 2, 3, 4, 5];
console.log("Duplicate array is:")
console.log(duplicateArray);
OutputDuplicate 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.
Syntax:
str.concat(string2, string3, string4,......, stringN);
Example: In this example, we have used concat() method
JavaScript
let originalArray = [1, 2, 3, 4, 5];
let duplicateArray = [].concat(originalArray);
console.log("Duplicate array is:")
console.log(duplicateArray);
OutputDuplicate 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.
Syntax:
let variablename1 = [...value];
Example: In this example, we have used Spread operator
JavaScript
let originalArray = [1, 2, 3, 4, 5];
let duplicateArray = [...originalArray];
console.log("Duplicate array is:")
console.log(duplicateArray);
OutputDuplicate 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.
Syntax:
JSON.parse( string, function )
JSON.stringify(value, replacer, space);
Example: In this example, we have used JSON.parse() and JSON.stringify()
JavaScript
let originalArray = [1, 2, 3, 4, 5];
let duplicateArray = JSON.parse(JSON.stringify(originalArray));
console.log("Duplicate array is:")
console.log(duplicateArray);
OutputDuplicate 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.
Syntax:
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.
JavaScript
function duplicateArray(arr) {
let duplicate = [];
for (let i = 0; i < arr.length; i++) {
duplicate[i] = arr[i];
}
return duplicate;
}
// Example usage:
let originalArray = [1, 2, 3, 4, 5];
let newArray = duplicateArray(originalArray);
console.log(newArray);
Conclusion:
- In conclusion, the fastest way to duplicate an array in JavaScript are using the slice() method and the spread operator, because they directly return a new array with the same elements as the original array, without any additional steps. They are considered as the most efficient way to duplicate an array.
- The second fastest method is Array.from(), which creates a new array with the same elements as the original array, but it's a little bit slower than the slice() and the spread operator.
- The concat() method and the for of loop are considered a bit slower than the previous methods because they iterate over the original array and add each element to a new array.
- The map() method is also considered a bit slower than the previous methods because it iterates over the original array and applies a function to each element.
- The slowest method is JSON.parse() and JSON.stringify(), it's considered one of the slowest method because it uses two methods and also it can only be used with JSON string, which may cause additional time and memory overhead.
Similar Reads
How to deep flatten an array in JavaScript?
In this article, we will learn how to deep flatten an array in JavaScript. The flattening of an array is a process of merging a group of nested arrays present inside a given array. Deep flattening means that the array would be completely flattened. Example: Input: [1,2,3,4,5,[6,[7,8,9]]] Output: [1,
2 min read
JavaScript - Unique Values (remove duplicates) in an Array
Given an array with elements, the task is to get all unique values from array in JavaScript. There are various approaches to remove duplicate elements, that are discussed below.get all unique values (remove duplicates) in a JavaScript array1. Using set() - The Best MethodConvert the array into a Set
2 min read
Different Ways to Crate an Array of Objects in JavaScript ?
Objects in JavaScript are key-value pairs, making them suitable for representing structured data. Also, an array in JavaScript is a versatile data structure that can hold a collection of values. When dealing with objects, an array can be used to store multiple objects. An array of objects allows you
3 min read
How to Remove Duplicate Objects from an Array in JavaScript?
In JavaScript, it's a common example that the arrays contain objects and there might be a possibility that the objects may or may not be unique. Removing these duplicate objects from the array and getting the unique ones is a common task in Web Development. These are the following approaches: Table
2 min read
How to clone an array in JavaScript ?
In JavaScript, cloning an array means creating a new array with the same elements as the original array without modifying the original array.Here are some common use cases for cloning an array:Table of ContentUsing the Array.slice() MethodUsing the spread OperatorUsing the Array.from() MethodUsing t
6 min read
Create an Array of Given Size in JavaScript
The basic method to create an array is by using the Array constructor. We can initialize an array of certain length just by passing a single integer argument to the JavaScript array constructor. This will create an array of the given size with undefined values.Syntaxcosnt arr = new Array( length );J
3 min read
Fastest way to convert JavaScript NodeList to Array
There are many ways to convert a NodeList to a JavaScript array but the fastest of all is a new method from ES6. In ES6, we can now simply create an Array from a NodeList using the Array.from() method. ApproachThe JavaScript Array.from() method is used to create a new array instance from a given arr
2 min read
How to Remove Duplicates from an Array of Objects in JavaScript?
Here are some effective methods to remove duplicates from an array of objects in JavaScript1. Using filter() and findIndex() Methods - Most UsedThe simplest way to remove duplicates is by using filter() and findIndex(). This method keeps the first occurrence of each object with a unique property (li
3 min read
How to Remove Duplicates in JSON Array JavaScript ?
In JavaScript, removing duplicates from a JSON array is important for data consistency and efficient processing. We will explore three different approaches to remove duplicates in JSON array JavaScript. Use the methods below to remove Duplicates in JSON Array JavaScript. Table of Content Using SetUs
3 min read
Javascript Program for Last duplicate element in a sorted array
We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7}Output :Last index: 4Last duplicate item: 6Input :
3 min read