Find index of an element in an array in Kotlin
This article explores different ways to find the index of an element in an array in Kotlin.
1. Using arrayOf() function
In Kotlin, you can use the indexOf() function that returns the index of the first occurrence of the given element, or -1 if the array does not contain the element.
|
1 2 3 4 5 6 7 8 9 10 |
fun findIndex(arr: Array<Int>, item: Int): Int { return arr.indexOf(item) } fun main() { val arr = arrayOf(1, 2, 3, 4, 5) val item = 2 println(findIndex(arr, item)) } |
2. Using firstOrNull() function
Another solution is to use the firstOrNull() function to return the index of the first occurrence of the element or null when an element is not found.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun findIndex(arr: Array<Int>, item: Int): Int? { return (arr.indices) .firstOrNull { i: Int -> item == arr[i] } } fun main() { val arr = arrayOf(1, 2, 3, 4, 5) val item = 2 println(findIndex(arr, item)) } |
3. Linear search
Another possible way is to perform a linear search on the array to check if the target element is present in the array or not.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun findIndex(arr: Array<Int>, item: Int): Int { for (i in arr.indices) { if (arr[i] == item) { return i } } return -1 } fun main() { val arr = arrayOf(1, 2, 3, 4, 5) val item = 2 println(findIndex(arr, item)) } |
That’s all about finding the index of an element in an array in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)