Skip to content

Arrays

Instance methods on arrays. All methods support chaining.

Methods

MethodReturnsDescription
len()intElement count
push(val)Append element
pop()intRemove and return last
first()intFirst element
last()intLast element
min()intMinimum value
max()intMaximum value
sum()intSum of all elements
slice(start, end)arraySub-array
sort()arraySorted copy
reverse()arrayReversed copy
unique()arrayDeduplicated copy
concat(other)arrayConcatenate arrays
join(sep)stringJoin with separator
index_of(val)intFind element (-1 if missing)
remove(idx)Remove at index
insert(idx, val)Insert at index
map(fn)arrayTransform elements
filter(fn)arrayFilter elements
reduce(fn, init)intFold elements
each(fn)Call fn for each element
any(fn)intAny element matches (1/0)
every(fn)intAll elements match (1/0)
sort_by(cmp_fn)Sort with comparator

Indexing and Slicing

Index from the front with a[i], or from the back with a negative index — a[-1] is the last element:

wyn
var a = [10, 20, 30, 40]
println(a[0].to_string())    // 10
println(a[-1].to_string())   // 40 — last
println(a[-2].to_string())   // 30 — second to last

Slice with a[i:j]. Either bound can be omitted:

wyn
var a = [10, 20, 30, 40, 50]
var head = a[:2]             // [10, 20]      — first two
var tail = a[2:]             // [30, 40, 50]  — from index 2
var mid  = a[1:4]            // [20, 30, 40]
var copy = a[:]              // full copy

println(tail[-1].to_string())  // 50 — negative index works on slices too

Membership: in

Test whether an array contains a value with in / not in:

wyn
var langs = ["python", "go", "rust"]
if "go" in langs { println("go supported") }
if "java" not in langs { println("no java") }

Method Chaining

wyn
// Chain any combination of array methods
var result = [3, 1, 4, 1, 5, 9].sort().reverse()
println(result[0].to_string())  // 9

var count = [5, 3, 1, 4, 2].filter(fn(x: int) -> bool { return x > 2 }).sort().len()
println(count.to_string())  // 3

var words = "hello world foo".split(" ").sort().join(", ")
println(words)  // foo, hello, world

Functional

wyn
var doubled = nums.map(fn(x: int) -> int { return x * 2 })
var big = nums.filter(fn(x: int) -> bool { return x > 3 })
var total = nums.reduce(fn(acc: int, x: int) -> int { return acc + x }, 0)

Comprehensions

wyn
var squares = [x * x for x in 0..10]
var evens = [x for x in 0..20 if x % 2 == 0]

See Also

  • Strings.join() arrays into strings
  • Log — structured logging
  • HashMap — key-value alternative to arrays
  • Control Flowfor-in loops over arrays

MIT License — v1.16