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;
};
_.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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With