Files
cell/docs/library/array.md

3.1 KiB

title, description, weight, type
title description weight type
array Array creation and manipulation 30 docs

The array function is an intrinsic (always available, no use() needed). It is polymorphic — its behavior depends on the type of the first argument.

From a Number

Create an array of a given size.

array(number)

All elements initialized to null.

array(3)  // [null, null, null]

array(number, initial)

All elements initialized to a value. If initial is a function, it is called for each element (passed the index if arity >= 1).

array(3, 0)           // [0, 0, 0]
array(3, i => i * 2)  // [0, 2, 4]

From an Array

Copy, map, concat, or slice.

array(array)

Copy an array (mutable).

var copy = array(original)

array(array, function)

Map — call function with each element, collect results.

array([1, 2, 3], x => x * 2)  // [2, 4, 6]

array(array, from, to)

Slice — extract a sub-array. Negative indices count from end.

array([1, 2, 3, 4, 5], 1, 4)  // [2, 3, 4]
array([1, 2, 3], -2)          // [2, 3]

array(array, another)

Concatenate two arrays.

array([1, 2], [3, 4])  // [1, 2, 3, 4]

From a Record

array(record)

Get the keys of a record as an array of text.

array({a: 1, b: 2})  // ["a", "b"]

From Text

array(text)

Split text into individual characters (grapheme clusters). This is the standard way to iterate over characters in a string.

array("hello")  // ["h", "e", "l", "l", "o"]
array("ƿit")    // ["ƿ", "i", "t"]

array(text, separator)

Split text by a separator string.

array("a,b,c", ",")  // ["a", "b", "c"]

array(text, length)

Dice text into chunks of a given length.

array("abcdef", 2)  // ["ab", "cd", "ef"]

Methods

array.for(arr, fn, reverse, exit)

Iterate over elements.

array.for([1, 2, 3], function(el, i) {
  print(i, el)
})

// With early exit
array.for([1, 2, 3, 4], function(el) {
  if (el > 2) return true
  print(el)
}, false, true)  // prints 1, 2

array.find(arr, fn, reverse, from)

Find element index.

array.find([1, 2, 3], 2)              // 1
array.find([1, 2, 3], x => x > 1)     // 1
array.find([1, 2, 3], x => x > 1, true) // 2 (from end)

array.filter(arr, fn)

Filter elements.

array.filter([1, 2, 3, 4], x => x % 2 == 0)  // [2, 4]

array.reduce(arr, fn, initial, reverse)

Reduce to single value.

array.reduce([1, 2, 3, 4], (a, b) => a + b)      // 10
array.reduce([1, 2, 3, 4], (a, b) => a + b, 10)  // 20

array.sort(arr, select)

Sort array (returns new array).

array.sort([3, 1, 4, 1, 5])  // [1, 1, 3, 4, 5]

// Sort by field
array.sort([{n: 3}, {n: 1}], "n")  // [{n: 1}, {n: 3}]

// Sort by index
array.sort([[3, "c"], [1, "a"]], 0)  // [[1, "a"], [3, "c"]]

Map with array()

The array(arr, fn) form maps over elements:

array([1, 2, 3], x => x * 2)  // [2, 4, 6]

array([1, 2, 3], function(el, i) {
  return el + i
})  // [1, 3, 5]