How to use the reduce function to return a JavaScript array?

Estimated read time 1 min read

The reduce function in JavaScript can be used to perform an operation on an array and return a single value. However, with some modifications, it can also be used to return a new array based on the original array. Here’s an example:

const arr = [1, 2, 3, 4, 5];

const newArr = arr.reduce((acc, curr) => {
  acc.push(curr * 2);
  return acc;
}, []);

console.log(newArr); // Output: [2, 4, 6, 8, 10]

In this example, the reduce function takes two arguments: a callback function and an initial value for the accumulator. The callback function takes two parameters: the accumulator (acc) and the current element of the array (curr). In this case, the callback function pushes the current element multiplied by 2 into the accumulator array (acc). Finally, the function returns the accumulator at the end of the operation. The initial value for the accumulator is an empty array ([]), so the resulting output is a new array of doubled values.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply