Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Ruby Enumerable#each_slice in Javascript?

I am looking for an equivalent of Ruby's Enumerable#each_slice in Javascript.

I am already using the great underscore.js that has each(), map(), inject()...

Basically, in Ruby this great method does this :

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].each_slice(3) {|a| p a}

# outputs below
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]
like image 270
Nicolas Blanco Avatar asked Apr 20 '12 16:04

Nicolas Blanco


2 Answers

How about this:

Array.prototype.each_slice = function (size, callback){
  for (var i = 0, l = this.length; i < l; i += size){
    callback.call(this, this.slice(i, i + size));
  }
};

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].each_slice(3, function (slice){
  console.log(slice);
});

Output (in Node.js):

[ 1, 2, 3 ]
[ 4, 5, 6 ]
[ 7, 8, 9 ]
[ 10 ]
like image 145
Brandan Avatar answered Sep 28 '22 10:09

Brandan


I would modify Brandan's answer slightly to fit better within the environment of JavaScript plus underscore.js:

_.mixin({ "eachSlice": function(obj, size, iterator, context) {
    for (var i=0, l=obj.length; i < l; i+=size) {
      iterator.call(context, obj.slice(i,i+size), i, obj);
    } }});

Here's a demo.

like image 25
Mark Reed Avatar answered Sep 28 '22 11:09

Mark Reed