Array.findIndex
func Array.findIndex[T](xs: Array[T], f: func(T): bool): int | nullArray.findIndex returns the index of the first 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 first element and stops at the first elementfaccepts.
Basic examples
Array.findIndex([4, 9, 16, 25], { x > 10 }) // 2
Array.findIndex([4, 9, 16, 25], { x > 30 }) // nullCall it through . on any array:
let names = ["Ann", "Bob", "Cid"]
names.findIndex({ x.startsWith("B") }) // 1Scope
The callback runs from the first element and stops at the first match, so a side effect shows which elements it tested:
let seen: Array[int] = []
[4, 9, 16, 25].findIndex({ seen.push(x); x > 5 }) // 1
seen // [4, 9]With no match, it tests every element:
let seen: Array[int] = []
[4, 9, 16].findIndex({ seen.push(x); x > 30 }) // null
seen // [4, 9, 16]An empty array has no index to return. Annotate it so that T is known:
let empty: Array[string] = []
empty.findIndex({ x == "" }) // nullOnly the first match counts, even when several elements match:
[3, 8, 5, 8].findIndex({ x == 8 }) // 1The index counts elements, so in an array of graphemes it counts characters as the reader sees them:
let chars = String.graphemes("ant 🐜 hill")
chars.findIndex({ x == "🐜" }) // 4Test a field of a record:
type User = { name: string, age: int }
let users = [User{ name: "Ann", age: 15 }, User{ name: "Bob", age: 34 }]
users.findIndex({ x.age >= 18 }) // 1Test the member of a union with is:
type Circle = { r: float64 }
type Square = { side: float64 }
type Shape = Circle | Square
let shapes: Array[Shape] = [Circle{ r: 1.0 }, Square{ side: 2.0 }, Square{ side: 3.0 }]
shapes.findIndex({ x is Square }) // 1An array whose element type includes null can look for the first null:
let scores: Array[int | null] = [90, null, 75]
scores.findIndex({ x == null }) // 1Pass a named function, or an anonymous func with a typed parameter:
func isNegative(n: int): bool {
n < 0
}
[3, -1, 4].findIndex(isNegative) // 1
[3, -1, 4].findIndex(func(n: int): bool { n % 2 == 0 }) // 2A lambda captures the variables around it:
let limit = 10
[4, 12, 7].findIndex({ x > limit }) // 1In a pipeline, the array is the first argument:
"a,b,,c" | String.split(",") | Array.findIndex({ x == "" }) // 2Applications
Replace the first element that matches, and leave the array alone when none does:
type Task = { title: string, done: bool }
let tasks = [Task{ title: "write", done: true }, Task{ title: "test", done: false }]
let i = tasks.findIndex({ !x.done })
if i != null {
tasks[i] = Task{ ...tasks[i], done: true }
}
println(tasks)[Task{ title: "write", done: true }, Task{ title: "test", done: true }]Remove the first element that matches with Array.removeAt:
let queue = ["low", "high", "low", "high"]
let i = queue.findIndex({ x == "high" })
if i != null {
println(queue.removeAt(i))
}
println(queue)high
["low", "low", "high"]Split the lines of a message at the first blank line, into a header and a body:
let lines = ["From: ann", "To: bob", "", "Hello,", "Bob"]
let at = lines.findIndex({ x == "" }) ?? len(lines)
println(lines.slice(0, at))
println(lines.slice(Math.min(at + 1, len(lines)), len(lines)))["From: ann", "To: bob"]
["Hello,", "Bob"]Stop with a clear message when a required element is missing:
let columns = ["id", "name", "email"]
let emailAt = columns.findIndex({ x == "email" }) ?? panic("no email column")
println("email is column ${emailAt + 1}")email is column 3Properties and relations
Array.findIndex with an == test agrees with Array.indexOf. It finds an index exactly when Array.some is true, and the element at that index is what Array.find returns:
let xs = [5, 3, 8, 3]
for v in [3, 8, 7] {
assert(xs.findIndex({ x == v }) == xs.indexOf(v))
assert((xs.findIndex({ x == v }) != null) == xs.some({ x == v }))
}
let i = xs.findIndex({ x > 4 }) ?? panic("none")
assert(xs[i] == xs.find({ x > 4 }))No element before the index found passes the test, and the first index is never after the last one that Array.findLastIndex finds:
let xs = [1, 4, 6, 9, 12]
let i = xs.findIndex({ x % 3 == 0 }) ?? panic("none")
assert(!xs.slice(0, i).some({ x % 3 == 0 }))
assert(i <= (xs.findLastIndex({ x % 3 == 0 }) ?? panic("none")))The same index comes out of Array.entries and Array.find:
let xs = ["ant", "bee", "cicada"]
let e = xs.entries().find({ x.value.length() > 3 })
assert(e?.index == xs.findIndex({ x.length() > 3 }))Possible issues
The result can be null, and the type checker rejects it as an index until you narrow it:
let xs = [1, 2, 3]
println(xs[xs.findIndex({ x == 2 })]) // error: cannot use int | null where int is expectedNor is it a condition. Ant has no truthiness, and index 0 is a match like any other. Compare with null instead:
if [1, 2, 3].findIndex({ x == 2 }) { // error: cannot use int | null where bool is expected
println("found")
}[1, 2, 3].findIndex({ x == 1 }) != null // true
[1, 2, 3].findIndex({ x == 1 }) // 0A miss is null, not -1 as in JavaScript, so i == -1 is never true. This program passes the type checker and gives the wrong answer:
let i = [1, 2, 3].findIndex({ x == 9 })
if i == -1 {
println("missing")
} else {
println("found")
}foundCompare with null instead:
let i = [1, 2, 3].findIndex({ x == 9 })
if i == null {
println("missing")
} else {
println("found")
}missingf must return a bool. A callback that computes something else is a compile error:
println([1, 2, 3].findIndex({ x * 2 })) // error: cannot use int where bool is expectedArray.findIndex takes a test, not a value. To look for a value by ==, use Array.indexOf:
println([1, 2, 3].findIndex(2)) // error: cannot use int where func(int): bool is expectedA lambda needs the expected function type to know what x is. Bound with let and no annotation, it is a compile error. Annotate the variable:
let big = { x > 1 }
// error: a lambda needs an expected function type; annotate the variable or use func with typed parameters
println([1, 2, 3].findIndex(big))let big: func(int): bool = { x > 1 }
[1, 2, 3].findIndex(big) // 1The call visits the elements xs had when it started. Elements the callback pushes are not tested:
let xs = [1, 2, 3]
xs.findIndex({ xs.push(x * 10); x == 10 }) // null
xs // [1, 2, 3, 10, 20, 30]See also
Array.find · Array.findLast · Array.findLastIndex · Array.indexOf · Array.some · Array.entries · Array.removeAt · Array.get
