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

2019-02-14 15:59发布

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

[ 1, 5, 9, 21 ]

into this

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

I know I could forEach the array and collect the values to create a new array. Is there an elegant way to do that in _.lodash without using a forEach?

8条回答
Luminary・发光体
2楼-- · 2019-02-14 16:33

A fast approach using map would be:

const arr = [ 1, 5, 9, 21 ];

const grouped = arr.map((el, i) => [el, arr[i+1]]).slice(0, -1);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

查看更多
乱世女痞
3楼-- · 2019-02-14 16:36

If you're willing to use another functional library 'ramda', aperture is the function you're looking for.

Example usage taken from the ramda docs:

R.aperture(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [2, 3], [3, 4], [4, 5]]
R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
R.aperture(7, [1, 2, 3, 4, 5]); //=> []
查看更多
登录 后发表回答