Pretty much the title. I've had a couple ideas but none of them seemed to work out - I can't seem to understand what exactly the arguments for the reduce function need to be, even after reading documentation and examples.
I'm supposed to take an array as an argument and use reduce to return the reverse of the array.
You can use Array.prototype.concat():
[1, 2, 3].reduce((a, b) => [b].concat(a), [])
or with spread syntax:
[1, 2, 3].reduce((a, b) => [b, ...a], [])
However there already exist method to reverse array - Array.prototype.reverse().
You could just do this:
array.reduce((v,a) => { v.unshift(a); return v; }, []);
Simply adding it to the resulting array (at the front) will reduce the array and leave the last item in the front. But like everyone mentions, arrays already have a built-in method do deal with this: Array.reverse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With