Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index of an object in Ballerina Array?

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?

like image 557
Rivindu Madushan Avatar asked Nov 07 '22 04:11

Rivindu Madushan


1 Answers

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.

like image 154
Kevin Languasco Avatar answered Nov 15 '22 06:11

Kevin Languasco