5

Lodash has a nice chunk method for arrays; is there an equivalent for objects (associative arrays)? The imperative solution is pretty straight forward, but I'm just curious if there is a cleaner functional implementation?

Imperative solution:
Takes an object as input
Returns an array of objects with size number of properties

var chunk = function(input, size){
  var obj = {};
  var output = [];
  var counter = 0;
  for (var k in input) {
    if(!input.hasOwnProperty(k)){
      continue;
    }
    obj[k] = input[k];
    if (++counter % size === 0) {
      output.push(obj);
      obj = {};
    }
  }
  if (Object.keys(obj).length !== 0){
    output.push(obj);
  }
  return output;
};
1
  • 3
    Maybe you could use _.pairs, then chunk, and _.object at the end? Commented Jul 31, 2015 at 16:40

2 Answers 2

10
_.mixin({"chunkObj": function(input, size) {
    return _.chain(input).pairs().chunk(size).map(_.object).value();
}});

console.log(_.chunkObj({a:1,b:2,c:3,d:4,e:5}, 2))
2
  • Thanks! I just about had the same thing except I was trying to use indexBy. So _.object is similar to _.partial(_.indexBy, _, 0)? Commented Jul 31, 2015 at 17:08
  • 8
    Just want to add, with current lodash it becomes return _.chain(input).toPairs().chunk(size).map(_.fromPairs).value()
    – vangoz
    Commented May 15, 2017 at 11:36
0

When I used with my array, I found it was causing the second and third sections to be mapped differently.

var skills = {};
skills["administration"] = 0;
skills["mechanical-engineering"] = 0;
skills["zero-g-operations"] = 0;

A sample object from the first object from the chunkObj looks like:

0: administration: 0

Using a 3-way split, the second and third chunkObj response however looks like

1: mechanical-engineering,0:undefined
2: zero-g-operations,0:undefined

My fixed method that keeps chunks 2 and 3 the same as the first:

_.mixin({"chunkObj": function(input, size) {
    var chunked = _.chunk(_.keys(input), size);
    var ret = {};   
    _.each(chunked, function(key, i) {
        var chunkedObj = {};
        _.each(chunked[i], function(key) {
            chunkedObj[key] = input[key];
        });
        ret[i] = chunkedObj;
    }); 
    return ret;
}});

In this case, the third section correctly becomes

0: administration: 0
1: mechanical-engineering: 0
2: zero-g-operations: 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.