Snippet. Vala. How to Find, if an Element Exists in Array

Finding if an element exists in an array is very common task. Here is one solution to the problem in Vala.

Function: array_search

The function array_search will search an array for a given element and return the position at which the element is found.

//======================== START OF FUNCTION ==========================//
// FUNCTION: array_search                                              //
//=====================================================================//
    /**
     * Searches the array for a given value and returns the corresponding
     * position if successful.
     * @return int the position of the value, -1 if not in array
     */
int array_search(G needle, G[] haystack){
    int result = -1;
    for (int i=0; i < haystack.length; i++) {
        if(needle == haystack[i]) return i;
    }
    return result;
}
//=====================================================================//
// FUNCTION: array_search                                              //
//========================= END OF FUNCTION ===========================//

Note. If the element is not found in the array, -1 will be returned.

How to Use

int[] array = {5,2,1,4,5,3,7,9,8};

int position = array_search(1,array);

if (position != 1) {
    print("Element found at position:"+position.to_string());
} else {
print("Element NOT found in array!"); }

Updated on: 21 Nov 2024