Equivalent of Ruby Enumerable#each_slice in Javasc

2019-01-25 09:07发布

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]

3条回答
戒情不戒烟
2楼-- · 2019-01-25 09:14

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

查看更多
我命由我不由天
3楼-- · 2019-01-25 09:28

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.

查看更多
smile是对你的礼貌
4楼-- · 2019-01-25 09:35

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 ]
查看更多
登录 后发表回答