Help us understand the problem. What is going on with this article?

# chunk

Lodashとかであるやつです。

```const chunk = (array, n) =>
array.reduce(
(a, c, i) =>
i % n == 0 ? [...a, [c]] : [...a.slice(0, -1), [...a[a.length - 1], c]],
[]
);
```

```const array = Array.from({ length: 7 }, (v, k) => k);
chunk(array, 2);
// [ [ 0, 1 ], [ 2, 3 ], [ 4, 5 ], [ 6 ] ]
```

# divide

```const divide = (array, n) => {
const tbl = new Array(n);
for (let y = 0; y < n; y++) {
tbl[y] = new Array();
}
array.forEach((a, i) => {
tbl[(i + 1) % n].push(a);
});
return tbl;
};
```

```const array = Array.from({ length: 7 }, (v, k) => k);
divide(array, 2);
// [ [ 1, 3, 5 ], [ 0, 2, 4, 6 ] ]
```

ぐぐっても`chunk`みたいな処理しかでてこなかった。もっといい書き方ありそう。

コメントにて @ttatsf さんからイカしたコードをいただきました！かっこいい...!

```const chunk = n => xs =>
xs.reduce(
(acc, _, i) =>
i % n === 0 ? [ ...acc, xs.slice( i, i + n ) ]
: [...acc]
, []
)

const divide = n => xs =>
zipLongest( chunk( n )( xs ) )
const zipLongest = xs =>
xs.reduce( zipLonger, [])
const zipLonger = (xs, ys) =>
xs.length >= ys.length ? xs.map(
(e, i) => i >= ys.length ? [e].flat() : [ e, ys[i] ].flat()
)
: ys.map(
(e, i) => i >= xs.length ? [e].flat() : [ xs[i], e ].flat()
)

//使用例：
const n = 2
const xs = [ 0, 1, 2, 3, 4, 5, 6 ]
chunk( n )( xs )  // [ [ 0, 1 ], [ 2, 3 ], [ 4, 5 ], [ 6 ] ]
divide( n )( xs ) // [ [ 0, 2, 4, 6 ], [ 1, 3, 5 ] ]
```
サービスを作ったり、新しい技術を試したりすることが好きです。 基本的にJavaScript,HTML,CSSのフロントエンド周り、SEOやアクセス解析などのWeb全般が好きなのでそういう投稿が多めになると思いますが、よかったらフォーローしてください！
https://labelmake.jp/

https://sharefull.com
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away