6. Arrays
Arrays in MALDA are dynamic, zero-indexed collections that can hold values of any type. Learning the language? Start at Learn MALDA.
6.1 Array Declaration
Arrays are created using square brackets with comma-separated values:
var arr = [1, 2, 3, 4, 5];
var names = ["Alice", "Bob", "Charlie"];
var empty = [];
var mixed = [1, "two", 3.0, true]; // Arrays can hold mixed types
6.2 Array Access
Array elements are accessed using zero-based indexing:
var arr = [10, 20, 30];
io.print(arr[0]);
io.print(arr.length);
arr.append(40);
io.print(arr.length);
6.3 Array Operations
Dynamic Resizing
Arrays can grow and shrink dynamically:
var arr = [1, 2, 3];
arr[3] = 4; // Array automatically grows
// arr is now [1, 2, 3, 4]
Writing past the end fills the gap with null: after arr[6] = 7 the array above is [1, 2, 3, 4, null, null, 7]. A negative index raises Array index out of bounds., and so does a compound assignment such as arr[9] += 1, because it reads the element first. All backends behave the same way.
Multi-dimensional Arrays
MALDA supports multi-dimensional arrays (arrays of arrays):
var matrix = [[1, 2], [3, 4]];
var value = matrix[0][1]; // value = 2
matrix[1][0] = 5; // matrix is now [[1, 2], [5, 4]]
6.4 Array Methods
Arrays are objects with built-in methods:
append(item)
Adds an item to the end of the array and returns the array:
var arr = [1, 2];
arr.append(3);
io.print(arr.length);
map, filter, and reduce are below. Return to Learn MALDA if this is your first pass.
pop()
Removes and returns the last element:
var arr = [1, 2, 3];
var last = arr.pop(); // last = 3, arr is now [1, 2]
popOrNull()
Removes and returns the last element, or null when the array is empty:
var arr = [];
var value = arr.popOrNull(); // null
shift()
Removes and returns the first element:
var arr = [1, 2, 3];
var first = arr.shift(); // first = 1, arr is now [2, 3]
shiftOrNull()
Removes and returns the first element, or null when the array is empty:
var arr = [];
var value = arr.shiftOrNull(); // null
concat(otherArray)
Returns a new array containing elements from both arrays:
var a = [1, 2];
var b = [3, 4];
var c = a.concat(b); // c is [1, 2, 3, 4], a and b unchanged
except(otherArray)
Returns a new array of elements from this array that are not in otherArray. Order and duplicates from the receiver are kept; the original arrays are unchanged. Membership uses the same equality as includes:
var a = [1, 2, 2, 3];
var b = [2];
var c = a.except(b); // c is [1, 3], a and b unchanged
var kept = [1, 1, 2].except([2]); // [1, 1]
map(fn)
Returns a new array with each element transformed by the function:
var doubled = [1, 2, 3].map(x => x * 2); // [2, 4, 6]
var squared = [1, 2, 3].map(x => x * x); // [1, 4, 9]
filter(fn)
Returns a new array containing only elements that match the predicate:
var evens = [1, 2, 3, 4].filter(x => x % 2 == 0); // [2, 4]
var positives = [-1, 2, -3, 4].filter(x => x > 0); // [2, 4]
reduce(fn, initialValue?)
Reduces the array to a single value by applying the function to each element:
var sum = [1, 2, 3].reduce((acc, x) => acc + x, 0); // 6
var product = [2, 3, 4].reduce((acc, x) => acc * x, 1); // 24
var max = [3, 1, 4, 2].reduce((acc, x) => x > acc ? x : acc); // 4
forEach(fn)
Iterates over each element and calls the function (for side effects):
[1, 2, 3].forEach(x => print(x)); // Prints 1, 2, 3
find(fn)
Returns the first element that matches the predicate, or null if none found:
var found = [1, 2, 3].find(x => x > 1); // 2
var notFound = [1, 2, 3].find(x => x > 10); // null
findIndex(fn)
Returns the index of the first element that matches the predicate, or -1 if none found:
var idx = [1, 2, 3].findIndex(x => x > 1); // 1
var notFound = [1, 2, 3].findIndex(x => x > 10); // -1
some(fn)
Returns true if at least one element matches the predicate:
var hasEven = [1, 2, 3].some(x => x % 2 == 0); // true
var allOdd = [1, 3, 5].some(x => x % 2 == 0); // false
every(fn)
Returns true if all elements match the predicate:
var allPositive = [1, 2, 3].every(x => x > 0); // true
var allEven = [1, 2, 3].every(x => x % 2 == 0); // false
sort(comparator?)
Sorts the array in place. With a comparator function, sorts according to the comparison result (negative if a < b, 0 if equal, positive if a > b). Without a comparator, uses default comparison:
var arr = [3, 1, 2];
arr.sort((a, b) => a - b); // arr is now [1, 2, 3]
var names = ["Charlie", "Alice", "Bob"];
names.sort(); // Default string comparison: ["Alice", "Bob", "Charlie"]
reverse()
Reverses the array in place and returns the array:
var arr = [1, 2, 3];
arr.reverse(); // arr is now [3, 2, 1]
slice(start, end?)
Returns a new array containing elements from start index (inclusive) to end index (exclusive). If end is omitted, includes all elements to the end. Negative indices count from the end:
var arr = [1, 2, 3, 4, 5];
var sub = arr.slice(1, 3); // [2, 3]
var rest = arr.slice(2); // [3, 4, 5]
var lastTwo = arr.slice(-2); // [4, 5]
get(index, fallback?)
Returns the element at index, or the optional fallback when out of bounds. Negative indices count from the end:
var arr = [10, 20, 30];
print(arr.get(1)); // 20
print(arr.get(-1)); // 30
print(arr.get(10, "n/a")); // n/a
at(index)
Returns the element at index, or null when out of bounds. Negative indices count from the end:
var arr = [10, 20, 30];
print(arr.at(0)); // 10
print(arr.at(-1)); // 30
print(arr.at(9)); // null
indexOf(value)
Returns the index of the first occurrence of value, or -1 if not found:
var idx = [1, 2, 3].indexOf(2); // 1
var notFound = [1, 2, 3].indexOf(5); // -1
includes(value)
Returns true if the array contains value:
var hasTwo = [1, 2, 3].includes(2); // true
var hasFive = [1, 2, 3].includes(5); // false
join(separator?)
Joins array elements into a string with the specified separator (default: ","):
var arr = ["a", "b", "c"];
var str = arr.join(); // "a,b,c"
var str2 = arr.join("-"); // "a-b-c"
6.5 Numeric Array Aggregation
For numeric arrays, MALDA also provides built-in aggregation helpers:
var scores = [10, 20, 30];
var total = sum(scores); // 60
var avg = average(scores); // 20.0
var smallest = min(scores); // 10
var largest = max(scores); // 30
var total2 = scores.sum(); // 60
var avg2 = scores.average(); // 20.0
var smallest2 = scores.min(); // 10
var largest2 = scores.max(); // 30
sum(array) returns the total of a numeric array. average(array) returns the arithmetic mean of a non-empty numeric array as a float. min(array) and max(array) return the smallest and largest numeric element in a non-empty numeric array.
The same operations are also available as array methods: array.sum(), array.average(), array.min(), and array.max().
The scalar forms min(a, b) and max(a, b) are still available for comparing two numeric values.
6.6 Array Length
The length property returns the number of elements in the array:
var arr = [1, 2, 3, 4, 5];
print(arr.length); // Prints 5
6.7 Fixed-Size Numeric Buffers (buf.*)
A buffer is a fixed-length run of numbers of one type, for numeric work and binary data. buf.float64(n), buf.float32(n), buf.int32(n) and buf.bytes(n) (unsigned 8-bit) make one filled with zeros; buf.from(array, kind?) copies an array or another buffer (kind is "float64", the default, "float32", "int32" or "uint8"). On JavaScript a buffer is a typed array (Float64Array, …), which makes numeric loops much faster there; the interpreter and C# transpile behave the same.
var grid = buf.float64(2000); // 2000 zeros, fixed length
for (var i = 0; i < grid.length; i = i + 1) {
grid[i] = math.sin(i * 0.01);
}
var total = 0.0;
for (var x in grid) {
total = total + x;
}
var counts = buf.int32(10);
counts[3] += 1;
print(counts); // [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
print(buf.toArray(grid).length); // 2000: a plain array for map / filter / append
- Like an array:
b[i],b[i] = v,b[i] += v,b[i]++,b.length,for (var x in b),print/stringas[1, 2],toJSONas a JSON array,length(b).typeOf(b)is"buffer";==compares identity. - Unlike an array: the length never changes. An index out of range is an error on read and on write (an array pads a write past the end with
null). A written value must be a number. There are no array methods:b.append,b.map… are errors;buf.toArray(b)gives a plain array. - Element types:
float32rounds what you store (0.1reads back as0.10000000149011612);int32anduint8truncate toward zero and wrap (modulo 232 and 28, sobytes[0] = 257stores 1), like JavaScript typed arrays. - Helpers:
buf.kind(b),buf.slice(b, start, end?)(a copy),buf.fill(b, value)(returnsb),buf.transfer(b)(returnsb, marked to be moved instead of copied when it next crosses a worker actor boundary).
Binary data
On a buf.bytes buffer, buf.readAt(bytes, offset, type) and buf.writeAt(bytes, offset, type, value) read and write a little-endian int8, uint8, int16, uint16, int32, uint32, float32 or float64; a range outside the buffer is an error. buf.fromUtf8(text) / buf.toUtf8(bytes) and buf.fromBase64(text) / buf.toBase64(bytes) convert to and from text.
var header = buf.bytes(8);
buf.writeAt(header, 0, "uint32", 1179011410);
buf.writeAt(header, 4, "float32", 1.5);
print(buf.toBase64(header)); // UklGRgAAwD8=
print(buf.readAt(header, 4, "float32")); // 1.5
print(buf.toUtf8(buf.fromUtf8("ciao"))); // ciao
See Also
- 8. Control Structures - Iterating over arrays with loops
- 12. Input/Output — console, files, paths, environment
- 4. Data Types - Dictionary types and
dict { ... }literals