LoginSignup
4
3

More than 5 years have passed since last update.

[Underscore.js] 配列を指定した個数の配列に分割する

Posted at

rubyでいうEnumerable#each_sliceのようなことをunderscore.jsでやりたかったんですが、ドンピシャ一発取りできる関数って用意されてないみたい・・。というわけで、メモっておきます。

以下の例は [1, 2, 3, 4, 5, 6, 7] を [[1, 2, 3],[4, 5, 6],[7]] に変換する例です。

var arr = [1, 2, 3, 4, 5, 6, 7];
var slice = 3;
return _.values(_.groupBy(arr, function(v, i) { return Math.floor(i / slice) }));
4
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3