Introduction
JavaScript is a prominent language utilized for web development. It is capable of executing a wide range of tasks. Furthermore, there are numerous functions available for sorting, scrolling, selecting, slicing, and searching through arrays. In this article, we will explore each of these functions through practical examples, and we will also discover the technique for duplicating an array.
In JavaScript, to modify an array, it is essential to generate a new array that mirrors the main or original array, containing identical elements.
In JavaScript, numerous techniques exist for duplicating an array. We will explore each approach to replicate an array utilizing the methods outlined below:
Array.slice
The Array.slice method is utilized to extract specific elements or values from the original array, effectively removing them. This method can be employed whenever certain values are deemed unnecessary. To use it, we must first delineate the array and create a copy by selecting designated starting and ending points.
The following code shows how to slice and Array.
const mainArray = [1, 2, 3];
const Array = mainArray.slice(1,2);
console.log(mainArray);
console.log(Array);
Output
When the slice method is called without any parameters, it creates a copy of the original array starting from a specified index and continuing to the end of the array. The resulting sliced array serves as a replica of the mainArray. In the example provided, the slice function yields "[2]" based on the values (1,2). The range of numbers spans from 0 to 2.
It is essential to understand that when utilizing the slice method with several arrays, what gets assigned are references rather than actual values.
Array.concat
This approach will yield a new array by combining, merging, or concatenating multiple arrays.
Let us discuss this concatenation method below:
num = [1, 5, 9]
//When we do not pass any values in this method it will produce the current array as an output.
numConcat = num.concat(5);
console.log(num)
console.log(numConcat)
Output
Array.map
The Array.map function produces an output that is an array of the same length as the input array. The map method creates a new array corresponding to each element in the original array. It will not function correctly if there is an empty element present. Furthermore, the map function leaves the original array unmodified.
const Array = [1, 2, 3, 4];
const clonedArray = Array.map(a => a);
console.log(clonedArray);
Output
This code snippet generates a duplicate of an array by utilizing the Array.map method. The map function applies a designated function to every element within the array, producing a new array that contains the results.
Array.filter
The Array.filter method, akin to map, generates a new array; however, the size of this new array may differ from the original. The filter function evaluates a provided function and a specified condition, returning the elements for which the condition holds true.
num = [5, 3, 5];
//filtering each entry in the num array, then allocating the element if the condition is {true}
numClone = num.filter(() => true);
// JavaScript array copy -> numClone from the array num
console.log(num)
console.log(numClone)
Output
The program described generates a duplicate of the array by employing the Array.filter method. The filter method assesses conditions within the nums array. When a condition is satisfied, the corresponding number is included in a new array referred to as numsClone.
Array.reduce
The Array.reduce method traverses each element within an array, ultimately generating a singular value or object that encapsulates the final result of the applied function.
Syntax:
array.reduce((accumulator, currentValue, currentIndex, array) => { ... }, initialValue);
num = [1, 4, 5]
// running a function and getting an array back by below:
numClone = num.reduce((normalArray, a) => {
normalArray.push(a)
return normalArray
}, []);
// JavaScript array copy -> numClone from the array num
console.log(num)
console.log(numClone)
Output
The reduce function is utilized to diminish the number of elements present in the aforementioned program. In this scenario, we initiate with an empty normalArray, and subsequently, we incrementally add each item from the "num" array. To ensure the method can be applied in the subsequent iteration, the array must be returned. The reference to the numClone array is returned as well. The elements of the number array will be replicated in the numClone array.
JSON.stringify and JSON.parse
The method JSON.stringify is utilized to convert an object into a string format, while the method JSON.parse is employed to transform a string back into an object. By utilizing these two functions in tandem, it is possible to take an item, convert it into a string, and subsequently revert it to a different type of data.
The functions JSON.parse and JSON.stringify serve the purpose of performing multilevel deep copying. These methods replicate values rather than references across all levels and are compatible with multi-dimensional arrays.
// below is an array which contains the array objects (2D arrays)
var Array1 = [[10, 20], [30], [40]]
var Array2 = JSON.parse(JSON.stringify(Array1))
// from below, we can see that only the Array2 changes and there will be no effect on the Array1.
Array2[1].push(50)
console.log(Array1)
// [ [ 10, 20 ], [ 30 ], [ 40 ] ] //it will remain the same as Array1
console.log(Array2)
// [ [ 10, 20 ], [ 30, 50 ], [ 40 ] ] modified
Output
The program mentioned above employs JSON.stringify to convert Array1 into a string representation. Subsequently, JSON.parse is utilized to transform this string back into a multi-dimensional array referred to as Array2. It is important to note that this approach generates a duplicate of the elements contained within the array. The resulting output demonstrates that modifications made to Array2 do not impact Array1.
Note: You can safely copy deep-nested arrays with this method.
Conclusion
- There are many methods for copying or cloning an array, such as loops, the spread operator (...), and array methods like slice, filter, reduce, and map.
- During deep copying, the array's reference is copied.
- parse and JSON.stringify are used for copying information at different levels. They work with multi-dimensional arrays and copy the values instead of references.