2

Is there any inbuilt function in ballerina to check if a value exists in an array?

I tried a simple function which iterate through a string array and checking the whether the value is present.

function isContain(string[] array1,string id) returns (boolean) {
    int i=0;
    int checker=-0;
    while (i<lengthof (array1)) {
        if(array1[i]==id){
            checker = 1;
            break;
        }
        i++;
    }
    if (checker == 1){
        return true;
    }
    else{
        return false;
    }
}
  • 2
    This question is a duplicate. See https://stackoverflow.com/questions/51201810/how-to-get-the-index-of-an-object-in-ballerina-array – Sameera Jayasoma Jul 06 '18 at 18:20
  • Your algorithem will perform at O(N) at worst case. If your string array is large, then I would recommend using the binary search algorithem which will perform at O(log N) – Sameera Jayasoma Jul 06 '18 at 18:22
  • Does this answer your question? [How to get the index of an object in Ballerina Array?](https://stackoverflow.com/questions/51201810/how-to-get-the-index-of-an-object-in-ballerina-array) – ThisaruG Nov 30 '22 at 06:18

1 Answers1

2

You can use indexOf() to solve this. You can write the isContain function as follows

function isContain(string[] array1, string id) returns boolean {
    return array1.indexOf(id) != ();
}