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]
1

3 Answers 3

13

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 ]
1
  • Give Mark Reed's answer a shot too. I'm not familiar with underscore.js.
    – Brandan
    Apr 20, 2012 at 17:01
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.

2
  • Sorry, how do I use this?
    – fabian
    Dec 13, 2015 at 14:22
  • first, the code assumes you're already using underscore.js; there's no _ object with a mixin method otherwise. If you've loaded underscore and run the above code, you will then have an _.eachSlice method that works as requested; see the jsfiddle demo linked in my answer.
    – Mark Reed
    Sep 13, 2017 at 12:47
6

I've found _.chunk in lodash is a better solution now

var chunk = require('lodash/array/chunk');

_.chunk(['a', 'b', 'c', 'd'], 2);
// -> [['a', 'b'], ['c', 'd']]

https://lodash.com/docs#chunk

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.