[removed] Make an array of value pairs form an array of values

前端 未结 8 1794
灰色年华
灰色年华 2021-01-06 08:40

Is there an elegant, functional way to turn this array:

[ 1, 5, 9, 21 ]

into this

[ [1, 5], [5, 9], [9, 21] ]

I kn

8条回答
  •  既然无缘
    2021-01-06 08:53

    You may do as follows with just a sinle liner of .reduce() with no initial;

    var arr = [ 1, 5, 9, 21 ],
      pairs = arr.reduce((p,c,i) => i == 1 ? [[p,c]] : p.concat([[p[p.length-1][1],c]]));
    console.log(pairs);

提交回复
热议问题