Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - using reduce to reverse an array

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.

like image 307
A_J Avatar asked Oct 22 '25 16:10

A_J


2 Answers

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().

like image 159
madox2 Avatar answered Oct 25 '25 04:10

madox2


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.

like image 21
somethinghere Avatar answered Oct 25 '25 06:10

somethinghere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!