最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - using reduce to reverse an array - Stack Overflow

programmeradmin1浏览0评论

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
  • 2 What is wrong with Array#reverse() ? – Rayon Commented Nov 1, 2016 at 15:37
  • 1 What the problem with array.reverse()? – BrTkCa Commented Nov 1, 2016 at 15:37
  • 1 Why on earth would you not just use the .reverse() method? Combine it with .slice() if you need a copy. – Alexander O'Mara Commented Nov 1, 2016 at 15:37
  • 3 The phrasing of their question seems to imply that this is some kind of task/challenge/code golf. – Joe Clay Commented Nov 1, 2016 at 15:38
  • 1 array.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
 |  Show 4 more comments

5 Answers 5

Reset to default 11

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.

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]));
发布评论

评论列表(0)

  1. 暂无评论