cluster
Split a list into many lists of the given size
116 bytes
since v12.1.0
Usage
Given an array of items and a desired cluster size (n
), returns an array
of arrays. Each child array containing n
(cluster size) items
split as evenly as possible.
import * as _ from 'radashi'
const gods = [ 'Ra', 'Zeus', 'Loki', 'Vishnu', 'Icarus', 'Osiris', 'Thor', 'Apollo', 'Artemis', 'Athena',]
_.cluster(gods, 3)// => [// [ 'Ra', 'Zeus', 'Loki' ],// [ 'Vishnu', 'Icarus', 'Osiris' ],// ['Thor', 'Apollo', 'Artemis'],// ['Athena']// ]
Type Inference
The cluster
function provides precise type inference for common cluster sizes (1-8):
// With explicit size parameterconst result1 = _.cluster(['a', 'b', 'c'], 1)// ^? [string][]
const result2 = _.cluster(['a', 'b', 'c', 'd'], 2)// ^? [string, string][]
const result3 = _.cluster(['a', 'b', 'c', 'd', 'e', 'f'], 3)// ^? [string, string, string][]
// Using default size parameter (2)const defaultSize = _.cluster(['a', 'b', 'c', 'd'])// ^? [string, string][]
// For sizes > 8, falls back to string[][]const largeSize = _.cluster(['a', 'b', 'c', 'd'], 10)// ^? string[][]
const veryLargeSize = _.cluster(['a', 'b', 'c', 'd'], 10000)// ^? string[][]