Categories
JavaScript Answers

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

Spread the love

To use the reduce function to return a JavaScript array, we return the array in the reduce callback.

For instance, we write

const store = [0, 1, 2, 3, 4];

const stored = store.reduce((pV, cV, cI) => {
  return [...pV, cV];
}, []);

console.log(stored);

to call store.reduce with a callback that destructures the pV array we get from the reduce process.

And then we spread the entries from there and the put cV at the end of it and return the array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *