Lodash - chunk method



Syntax

_.chunk(array, [size=1])

Creates an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements.

Arguments

  • array (Array) − The array to process.

  • [size=1] (number) − The length of each chunk.

Output

  • (Array) − Returns the new array of chunks.

Example

var _ = require('lodash');
var numbers = [1, 2, 3, 4];
var listOfNumbers = '';

listOfNumbers = _.chunk(numbers, 2);
console.log(listOfNumbers);

listOfNumbers = _.chunk(numbers, 3);
console.log(listOfNumbers);

Save the above program in tester.js. Run the following command to execute this program.

Command

\>node tester.js

Output

[ [ 1, 2 ], [ 3, 4 ] ]
[ [ 1, 2, 3 ], [ 4 ] ]
lodash_array.htm
Advertisements