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;
};
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;
};
Share
asked Jul 31, 2015 at 16:39
AndrewJesaitisAndrewJesaitis
4824 silver badges16 bronze badges
1
-
3
Maybe you could use
_.pairs
, then chunk, and_.object
at the end? – Platinum Azure Commented Jul 31, 2015 at 16:40
2 Answers
Reset to default 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))
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 bees
0: administration: 0
1: mechanical-engineering: 0
2: zero-g-operations: 0