How can I get the index of an object in a Ballerina array in an efficient way? Is there any inbuilt function to do that?
Ballerina now offers the indexOf
and lastIndexOf
methods, as of language specification 2020R1.
They return the first and last indices for items that satisfy the equality, respectively. We get ()
if the value is not found.
import ballerina/io;
public function main() {
string[*] example = ["this", "is", "an", "example", "for", "example"];
// indexOf returns the index of the first element found
io:println(example.indexOf("example")); // 3
// The second parameter can be used to change the starting point
// Here, "is" appears at index 1, so the return value is ()
io:println(example.indexOf("is", 3) == ()); // true
// lastIndexOf will find the last element instead
// (the implementation will do the lookup backwards)
io:println(example.lastIndexOf("example")); // 5
// Here the second parameter is where to stop looking
// (or where to start searching backwards from)
io:println(example.lastIndexOf("example", 4)); // 3
}
Run it in the Ballerina Playground
The description of these and other functions can be found in the spec.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With