How to use Array.reduce() Method In Javascript
The Array.reduce() method executes a reducer function on each element of the array, resulting in a single output value. We can use it to construct a new array with the same elements as the original array.
Syntax:
array.reduce((accumulator, currentValue, currentIndex, array) => { ... }, initialValue);
Example: In this example, we’ll use the Array.reduce() method to create a clone of an array.
// Input array
const originalArray = [1, 2, 3, 4];
// Cloning the array using reduce
const clonedArray = originalArray.reduce((acc, val) => {
acc.push(val);
return acc;
}, []);
// Display the original and cloned arrays
console.log("Original Array:", originalArray); // Output: [1, 2, 3, 4]
console.log("Cloned Array:", clonedArray); // Output: [1, 2, 3, 4]
Output
Original Array: [ 1, 2, 3, 4 ] Cloned Array: [ 1, 2, 3, 4 ]
Note: Thus, When cloning an array, it is important to consider the complexity of the data and the performance requirements of the application.
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. Cloning an array in JavaScript is useful when you want to create a new array that has the same elements as an existing array, without modifying the original array.
Contact Us