Table of Contents
1. Slice() Method
The alternative for copying an array is the slice() method, which generates a new array with only a portion of the elements in the original array. By gathering it without any statements, you can use this function to copy a whole array.
Using the slice(,) method to copy an array is demonstrated here:
The original array is the array you wish to copy. By naming the slice(,) method on the original array without any statements, it can generate a new array called copied array. By doing this, the array is made into a shallow copy, which means that identical elements from the original array are present in the new array but are not replicated.
Like the spread operator, the slice() function only makes a partial copy of an array. When an array has objects or arrays, the slice() method only makes a shallow copy of the top-level items; the elements splits between the original array and the copy.
2. JSON.parse() and JSON.stringify() Method
The following example demonstrates the use of JSON.parse() and JSON.stringify() to make a deep copy of an array:
The JSON.parse() and JSON.stringify() methods are dependable ways to make a deep copy of an array. But they can be slower and use more resources than the other methods, particularly for big or complex arrays.
3. Filter Method
The filter method only returns array components that satisfy the criteria specified in a callback function. Callback function is another technique to make a copy of an array. It requires a condition that will always be true if you are to copy all the elements. Return true for every element, much as how to use the map method earlier.
This code declares and initializes the original Array with the values 1, 2, and 3. The filter method on the original Array then invokes creation of a new array called copiedArray. The callback function in this scenario is an anonymous function that always returns true. In other words, every component of the original Array will pass the test and add to the newly copied Array.
See Also: Best Tools For Beautifying HTML, CSS, JS