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.
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.
Share Improve this question asked Nov 1, 2016 at 15:36 A_JA_J 751 silver badge3 bronze badges 9 | Show 4 more comments5 Answers
Reset to default 11You 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
.
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);
a.reduceRight((acc, cur) => { return acc.concat(cur) }, [])
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight
var reverseArray = function (arr) {
return list.reduce(function (list, current) {
list.unshift(current);
return list;
}, []);
};
console.log(reverseArray([1,2,3,4]));
Array#reverse()
? – Rayon Commented Nov 1, 2016 at 15:37array.reverse()
? – BrTkCa Commented Nov 1, 2016 at 15:37.reverse()
method? Combine it with.slice()
if you need a copy. – Alexander O'Mara Commented Nov 1, 2016 at 15:37array.reduce((v,a)=>{v.unshift(a);return v;}, [])
- But like everyone said,array.reverse
already does this. – somethinghere Commented Nov 1, 2016 at 15:40