array
The array function and its methods handle array creation and manipulation.
Creation
array(number)
Create an array of specified size, filled with null.
array(3) // [null, null, null]
array(number, initial)
Create an array with initial values.
array(3, 0) // [0, 0, 0]
array(3, i => i * 2) // [0, 2, 4]
array(array)
Copy an array.
var copy = array(original)
array(array, from, to)
Slice an array.
array([1, 2, 3, 4, 5], 1, 4) // [2, 3, 4]
array([1, 2, 3], -2) // [2, 3]
array(array, another)
Concatenate arrays.
array([1, 2], [3, 4]) // [1, 2, 3, 4]
array(object)
Get keys of an object.
array({a: 1, b: 2}) // ["a", "b"]
array(text)
Split text into grapheme clusters.
array("hello") // ["h", "e", "l", "l", "o"]
array("👨👩👧") // ["👨👩👧"]
array(text, separator)
Split text by separator.
array("a,b,c", ",") // ["a", "b", "c"]
array(text, length)
Split text into chunks.
array("abcdef", 2) // ["ab", "cd", "ef"]
Methods
array.for(arr, fn, reverse, exit)
Iterate over elements.
array.for([1, 2, 3], function(el, i) {
log.console(i, el)
})
// With early exit
array.for([1, 2, 3, 4], function(el) {
if (el > 2) return true
log.console(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]