How to use reduce to double the elements of an array in Javascript?
How to use reduce to double the elements of an array in Javascript?
18427-Mar-2023
Updated on 28-Mar-2023
Home / DeveloperSection / Forums / How to use reduce to double the elements of an array in Javascript?
How to use reduce to double the elements of an array in Javascript?
Amrita Bhattacharjee
28-Mar-2023To use the reduce method to double the elements of an array,we can use the following code:
Here , we have used arr to define the values of an array. After this we used the reduce method on the specific array elements through using a pass in callback function being the first argument.
The callback function is consisting with two of the acc which is used for accumulator and curr which is used for current element.
Here we used the push method in the callback function to push the doubled value of the curr into acc.Then we returned the accumulator array.
The second argument is passed to the reduce is considered as an empty array that is being as initial level value of the acc.It shows that the initial call to the callback function has an accumulator value of the empty array and a currrent element value of the initial element in the original array.
The final output of using the reduce method is an array consisting of the doubled values of the original array.