A_J
A_J

Reputation: 75

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.

Upvotes: 4

Views: 8237

Answers (5)

FluffyBeing
FluffyBeing

Reputation: 468

a.reduceRight((acc, cur) => { return acc.concat(cur) }, []) 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight

Upvotes: 1

Redu
Redu

Reputation: 26191

You can simply do like this;

var arr = [1,2,3,4,5],
    brr = arr.reduce((p,c) => [c].concat(p));
console.log(brr);

...or one other way

var arr = [1,2,3,[4],5],
    brr = arr.reduce((p,c,i) => i-1 ? [c,...p] : [c,p]);
console.log(brr);

Upvotes: 2

Thalaivar
Thalaivar

Reputation: 23642

var reverseArray = function (arr) {
  return list.reduce(function (list, current) {
    list.unshift(current);
    return list;
  }, []);
};

console.log(reverseArray([1,2,3,4]));

Upvotes: 0

somethinghere
somethinghere

Reputation: 17350

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.

Upvotes: 2

madox2
madox2

Reputation: 51881

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

Upvotes: 11

Related Questions