Arrays
Keep lists of values, read and change them by position, and transform them with map, filter and friends.
An array is an ordered list of values. Write the element type followed by [], and the items in square brackets:
string[] planets = ["Mercury", "Venus", "Earth", "Mars"]
log planets
log planets.len.len is the number of items. It's a property, so it has no brackets.
Counting from one#
The first item is at position 1. Negative positions count back from the end, so the last item is always [-1]:
string[] planets = ["Mercury", "Venus", "Earth", "Mars"]
log planets[1]
log planets[3]
log planets[-1]
planets[3] = "Home"
log planetsThere's no position 0, and the compiler says so when it sees one:
string[] planets = ["Mercury", "Venus"]
log planets[0]Adding and removing#
int[] queue = [2, 3]
queue.append(4)
queue.prepend(1)
log queue
int last = queue.pop()
int first = queue.shift()
log last first queue
queue.insert(2, 99)
log queue
queue.delete(2)
log queueappend adds to the end and prepend to the start. pop removes and returns the last item, shift the first. insert(position, value) puts a value in at a position, and delete(position) takes one out.
Looking inside#
string[] fruit = ["apple", "pear", "plum"]
log fruit.contains("pear")
log fruit.index("plum")
log fruit.index("kiwi")
log fruit.first() fruit.last()Like strings, index returns 0 when the value isn't there.
Ranges#
to makes an array of whole numbers, counting up or down, with both ends included:
log 1 to 5
log 5 to 1
int[] evens = (1 to 10).filter(n -> n % 2 == 0)
log evensTransforming arrays#
The most useful array methods take a small function and apply it to every item. n -> n * 2 is a function that takes n and returns n * 2; the lambdas lesson covers them properly.
int[] prices = [12, 5, 30, 8]
log prices.map(p -> p * 2)
log prices.filter(p -> p < 10)
log prices.some(p -> p > 25)
log prices.every(p -> p > 1)
log prices.sum() prices.min() prices.max()mapmakes a new array from what the function returns for each item.filterkeeps the items the function saystruefor.someasks whether any item passes, andeverywhether all of them do.sum,minandmaxdo what they say.
They chain, reading left to right like a sentence:
string[] names = ["ada", "grace", "al", "linus"]
log names.filter(n -> n.len > 2).map(n -> n.toUpper()).join(", ")Sorting#
sort returns a sorted copy: numbers in numeric order, everything else alphabetically. reverse flips the order:
int[] scores = [42, 7, 19, 88]
log scores.sort()
log scores.sort().reverse()
log ["pear", "apple", "fig"].sort()Joining and spreading#
++ joins two arrays, and ... spreads one array's items into another:
int[] low = [1, 2]
int[] high = [8, 9]
log low ++ high
log [...low, 5, ...high]
log max(...high)Taking arrays apart#
Destructuring puts an array's items straight into variables. ...rest collects whatever is left:
string[] podium = ["Ada", "Grace", "Linus", "Margaret"]
[string gold, string silver, ...others] = podium
log gold
log silver
log othersSharing and copying#
An array is shared, not copied, when you assign it to another name. Both names then see the same list:
int[] a = [1, 2, 3]
int[] b = a
b.append(4)
log a
int[] c = a.clone()
c.append(5)
log a
log cUse .clone() when you want a separate copy to change.
Arrays of anything#
int[] and string[] hold one type each, which is what you want most of the time. Arrays can hold arrays, as in int[][] for a grid, and plain array holds a mix of types:
int[][] grid = [[1, 2], [3, 4]]
log grid[2][1]
array mixed = [1, "two", true]
log mixed.lenint[] n = [10, 20, 30]. What is n[-1]?
What does [3, 1, 2].filter(x -> x > 1).sort() give?
Top three
Print the three highest scores, highest first, joined with commas.
99, 91, 88