Alex Rivera | Logout

Equivalent of Ruby Enumerable#each_slice in Javascript?

Asked 2012-04-20T16:06:37.483
16

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]
Edit
Report

1 Answer

11

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.

answered 2012-04-20T16:31:54.403

Your Answer