mymotherland
mymotherland

Reputation: 8226

lodash split array into chunk in nodejs

I have below group with contacts

 var groups = {"GROUP":[{'G1: [C1,C2,C3........C500000]},
             {'G2': [C1,C2,C3........C500000,D1,D2,D3........D500000]}
.....]
    }

Now i am split a javascript array into n sized chunks using lodash as like below

_.each(groups,function(group){
 var n = 50;
var lists = _.groupBy(group, function(element, index){
  return Math.floor(index/n);
});
lists = _.toArray(lists );
console.log(lists )
})

This works fine in client end but not in nodejs. Output from node js as below

[["C1","C1....]]

Array is not split in to chunks instead it is coming as single array.

Expected array should be

[["C1","C1"....,"c50"],["C51","C1"....,"c100"]...]

I am using lodash 4.17.4 in nodejs.Please advise

Upvotes: 4

Views: 3730

Answers (1)

Lodewijk Bogaards
Lodewijk Bogaards

Reputation: 19987

This must have something to do with using a different version in the browser than in node, because if you look at the code of groupBy in Lodash 4.17.4 you can clearly see that the function you pass in, the iteratee, is only called with one argument, namely the key, and not the key and the index:

function groupBy(collection, iteratee) {
  return reduce(collection, (result, value, key) => {
    key = iteratee(value) // <- no index here
    if (hasOwnProperty.call(result, key)) {
      result[key].push(value)
    } else {
      baseAssignValue(result, key, [value])
    }
    return result
  }, {})
}

Looking at all the git history of groupBy.js I am not surprised the behavior has changed over time. Some time ago it was changed completely from using some generic iteratee, which would likely include the index, to something much more simple that obviously does not include the index.

If I were you I would achieve this chunking behavior with a reduce statement:

function chunkArray(array, chunkSize) {
  return _.reduce(array, function(result, value) {
    var lastChunk = result[result.length-1];
    if (lastChunk.length < chunkSize) lastChunk.push(value);
    else result.push([value]);
    return result;
  }, [[]]);
}

Upvotes: 1

Related Questions