Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chunking Objects in functional style (Underscore/Lodash)

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;
};
like image 965
AndrewJesaitis Avatar asked Jan 08 '23 20:01

AndrewJesaitis


1 Answers

_.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))
like image 71
homam Avatar answered Feb 01 '23 13:02

homam