/array-chunker

Chunks an array into n groups

Primary LanguageJavaScriptMIT LicenseMIT

array-chunker

Evenly distributes array values into an array of n arrays.

Usage

const arrayChunk = require('array-chunker');
const arr = [0, 1, 2, 3, 4, 5, 6, 7];

arrayChunk(arr)
=> [[0, 1, 2, 3], [4, 5, 6, 7]]

arrayChunk(arr, 4);
=> [[0, 1], [2, 3], [4, 5], [6, 7]]

When there aren't even chunks

Number.isInteger(arr.length / n)
=> false
arrayChunk(arr, 3);
=> [[0, 1, 2], [3, 4, 5], [6, 7]]

arrayChunk(arr, 5);
=> [[0, 1], [2, 3], [4, 5], [6], [7]]
arr.length < n
=> true

arrayChunk(arr, 10);
=> [[0], [1], [2], [3], [4], [5], [6], [7], [], []]

An empty array

// n defaults to 2
arrayChunk([]);
=> [[], []];

arrayChunk([], 3);
=> [[], [], []];

No array

arrayChunk();
=> [];

Docs

arrayChunk(data, n) ⇒ Array

Param Type Default Description
arr Array The array to be chunked.
[n] Integer 2 The number of new arrays.