Array.findLastIndex
func Array.findLastIndex[T](xs: Array[T], f: func(T): bool): int | nullArray.findLastIndex returns the index of the last element of xs that f accepts, or null when there is none.
Details
- Returns
nullwhenfaccepts no element, so an empty array givesnull. - Calls
ffrom the last element back and stops at the first elementfaccepts.
Basic examples
Find the position of the last number above 5:
Array.findLastIndex([3, 8, 1, 9, 4], { x > 5 }) // 3When f accepts no element, the result is null:
Array.findLastIndex([3, 8, 1], { x > 50 }) // nullCall it through . on any array:
let words = ["ant", "bee", "wasp", "fly"]
words.findLastIndex({ x.length() == 3 }) // 3
words.findLastIndex({ x.startsWith("b") }) // 1Scope
An empty array has no last match. Annotate it so that T is known:
let empty: Array[int] = []
empty.findLastIndex({ x > 0 }) // nullA one-element array gives 0 or null:
[7].findLastIndex({ x == 7 }) // 0
[7].findLastIndex({ x == 8 }) // nullWhen f accepts every element, the result is the last index:
[1, 2, 3].findLastIndex({ x > 0 }) // 2Strings are tested whole. Split them into graphemes to search by character:
let letters = "naïve café".graphemes()
letters.findLastIndex({ x == "é" || x == "ï" }) // 9An array whose element type includes null can look for the last null:
let readings: Array[int | null] = [12, null, 15, null, 9]
readings.findLastIndex({ x == null }) // 3
readings.findLastIndex({ x != null && x > 10 }) // 2Records are tested through their fields:
type Task = { name: string, done: bool }
let tasks = [
Task{ name: "plan", done: true },
Task{ name: "build", done: true },
Task{ name: "ship", done: false },
]
tasks.findLastIndex({ x.done }) // 1A function on a type works the same way:
type Task = { name: string, done: bool }
func Task.isOpen(t: Task): bool {
!t.done
}
let tasks = [
Task{ name: "plan", done: false },
Task{ name: "build", done: true },
Task{ name: "ship", done: false },
]
tasks.findLastIndex(Task.isOpen) // 2Members of a union are tested with is:
type Circle = { radius: float64 }
type Square = { side: float64 }
type Shape = Circle | Square
let shapes: Array[Shape] = [Circle{ radius: 1.0 }, Square{ side: 2.0 }, Circle{ radius: 3.0 }]
shapes.findLastIndex({ x is Square }) // 1
shapes.findLastIndex({ x is Circle && x.radius < 2.0 }) // 0A named function works where a lambda does:
func isEven(n: int): bool {
n % 2 == 0
}
[1, 2, 3, 4, 5].findLastIndex(isEven) // 3A call can name f:
Array.findLastIndex([4, 9, 2], f: { x > 3 }) // 1In a pipeline, the array is the first argument:
"a,b,,c,," | String.split(",") | Array.findLastIndex({ x != "" }) // 3Applications
Find the last error in a log and read the lines after it:
let log = ["start", "error: disk", "retry", "error: net", "retry", "ok"]
let i = log.findLastIndex({ x.startsWith("error") })
if i != null {
println(log[i])
println(log.slice(i + 1, len(log)))
}error: net
["retry", "ok"]Trim trailing blank lines from a text:
func trimTrailing(lines: Array[string]): Array[string] {
let last = lines.findLastIndex({ x.trim() != "" }) ?? -1
lines.slice(0, last + 1)
}
println(trimTrailing(["one", "two", "", " "]))
println(trimTrailing(["", ""]))["one", "two"]
[]Find the last day a sensor reported a value above its limit:
type Reading = { day: string, value: float64 }
let readings = [
Reading{ day: "Mon", value: 18.5 },
Reading{ day: "Tue", value: 31.0 },
Reading{ day: "Wed", value: 22.0 },
Reading{ day: "Thu", value: 30.5 },
Reading{ day: "Fri", value: 19.0 },
]
let i = readings.findLastIndex({ x.value > 30.0 })
println(if i != null { "last over limit: ${readings[i].day}" } else { "never over limit" })last over limit: ThuProperties and relations
f sees the elements from the last back, and the search stops at the first one it accepts:
let xs = [3, 8, 1, 9, 4]
let i = xs.findLastIndex({
println("testing ${x}")
x > 5
})
println(i)testing 4
testing 9
3When f accepts no element, it has run once on each, last first:
let seen: Array[int] = []
let i = [1, 2, 3].findLastIndex({
seen.push(x)
x > 9
})
assert(i == null)
assert(seen == [3, 2, 1])The element at the index is the one Array.findLast returns:
let xs = [4, 11, 7, 15, 2]
func f(n: int): bool {
n > 10
}
let i = xs.findLastIndex(f)
assert(i != null)
assert(xs[i] == xs.findLast(f))
assert(xs.findLastIndex({ x > 100 }) == null && xs.findLast({ x > 100 }) == null)No element after the index is accepted, and the result is null exactly when Array.some is false:
let xs = [4, 11, 7, 15, 2]
for limit in [0, 5, 10, 20] {
let i = xs.findLastIndex({ x > limit })
assert((i != null) == xs.some({ x > limit }))
let from = (i ?? -1) + 1
assert(!xs.slice(from, len(xs)).some({ x > limit }))
}It mirrors Array.findIndex on the reversed array:
let xs = [3, 6, 1, 8, 5]
let j = xs.reverse().findIndex({ x % 2 == 0 })
assert(j != null)
assert(xs.findLastIndex({ x % 2 == 0 }) == len(xs) - 1 - j)With an == test it agrees with Array.lastIndexOf:
let xs = ["a", "b", "a", "c"]
for v in ["a", "c", "z"] {
assert(xs.findLastIndex({ x == v }) == xs.lastIndexOf(v))
}Possible issues
The result is nullable, so it cannot index the array as it is:
let xs = [5, 6, 7]
println(xs[xs.findLastIndex({ x > 5 })]) // error: cannot use int | null where int is expectedNor can it go straight into arithmetic:
let xs = [5, 6, 7]
println(xs.findLastIndex({ x > 5 }) + 1)
// error: + needs both operands of one type, got int | null and intTest it against null, not for truth. 0 is a valid index, and an int | null is not a condition:
let i = [5, 6].findLastIndex({ x == 5 })
if i { // error: cannot use int | null where bool is expected
println(i)
}let i = [5, 6].findLastIndex({ x == 5 })
i != null // true
i // 0f must return a bool. A value that is not one is a compile error, not a truth test:
println([0, 1, 2].findLastIndex({ x })) // error: cannot use int where bool is expectedNaN is not == to itself, so an == test never finds it. Test with Math.isNaN:
let xs = [Math.NaN, 1.0, Math.NaN, 2.0]
xs.findLastIndex({ x == Math.NaN }) // null
xs.findLastIndex({ Math.isNaN(x) }) // 2Because the search stops early, a callback is no place to count. Here f never sees the first 7, so it counts one; Array.countWhere counts both:
var sevens = 0
let xs = [2, 7, 4, 7, 1]
let i = xs.findLastIndex({
if x == 7 {
sevens += 1
}
x == 7
})
i // 3
sevens // 1
xs.countWhere({ x == 7 }) // 2A callback that pushes to the array does not make Array.findLastIndex test the new elements:
let xs = [1, 2, 3]
xs.findLastIndex({ xs.push(x + 10); x > 5 }) // nullSee also
Array.findIndex · Array.findLast · Array.find · Array.lastIndexOf · Array.indexOf · Array.some · Array.entries · Array.slice
