Arrays
Arrays are dynamic, ordered lists. They can hold mixed data types, resize automatically, and feature an extensive collection of utility methods.
Instantiation
let list = [10, "apple", True, [3, 4]]
print(list[0]) # => 10
print(list[3][1]) # => 4
Full Methods Catalog
| Method | Description |
|---|---|
length() | Number of elements |
append(value) | Add value at end |
pop(index?) | Remove and return element (last or at index) |
insert(index, val) | Insert at position, shifting elements |
remove(value) | Remove first occurrence of value |
reverse() | Reverse array in-place |
reversed() | Return new array in reverse order (original unchanged) |
index(value|cb) | Index of value or first element matching callback (-1 if not found) |
extend(array) | Append all elements from another array |
sort(descOrCmp?) | Sort array; accepts bool (descending) or comparator function |
sorted(desc?) | Return sorted copy (original unchanged) |
copy() | Return shallow copy of array |
clear() | Remove all elements |
contains(value) | Check if value exists in array |
count(value) | Count occurrences of value |
concat(other) | Return new array with elements from both |
slice(start, end?) | Extract sub-array |
join(sep) | Join elements into string with separator |
flatten() | Flatten nested arrays one level |
unique() | Return new array with duplicate values removed |
all() | All elements are truthy |
any() | Any element is truthy |
min() | Minimum value in array |
max() | Maximum value in array |
sum() | Sum of all numeric elements |
map(callback) | Transform each element, return new array |
filter(callback) | Keep elements where callback returns truthy |
reduce(callback, init) | Accumulate values into single result |
find(value) | Find first element matching value or callback (Null if not found) |
every(callback) | Check if all elements pass callback |
some(callback) | Check if any element passes callback |
Method Chaining Example
let numbers = [1, 2, 3, 4, 5, 6]
let result = numbers
.filter(fn(x) => x % 2 == 0)
.map(fn(x) => x * 10)
.sum()
print(result) # (2*10) + (4*10) + (6*10) => 120
Sort Variants
let arr = [5, 1, 9, 3]
arr.sort() # ascending: [1, 3, 5, 9]
arr.sort(True) # descending: [9, 5, 3, 1]
arr.sort(fn(x, y) => y - x) # custom comparator: [9, 5, 3, 1]