...

/

Solution Review: Search the First Occurrence of a Number

Solution Review: Search the First Occurrence of a Number

This review provides a detailed analysis of finding the first occurrence of the given number in an array.

Solution #1: Iterative Method

Press + to interact
function firstIndex(arr, testVariable, currentIndex) { // returns the first occurrence of testVariable
while (currentIndex < arr.length) { // Iterate over the array
if (arr[currentIndex] == testVariable) { // Return the current index if testVariable found
return currentIndex;
}
currentIndex += 1;
}
return -1;
}
// Driver Code
var arr = [9, 8, 1, 8, 1, 7];
var testVariable = 1;
var currentIndex = 0;
console.log(firstIndex(arr, testVariable, currentIndex));

Explanation

To find the first occurrence of testVariable we iterate over the entire array and return the currentIndex when testVariable is found. Let’s look at an illustration:

...

Access this course and 1400+ top-rated courses and projects.