Home > Blockchain >  Creating a function to search for a value in an array and return it's position index using a lo
Creating a function to search for a value in an array and return it's position index using a lo

Time:02-12

I'm very new to JavaScript. I'm trying to create a function that can two take two arguments, an array and a value. The function should return the index where the value is found but ff the value is not found, it should return -1. I want to this using a loop and not a method like for example indexOf.

So this is what I got by now:

function getIndex(arr, value) {
  for (let i = 0; i < arr.length; i  ) {
    if (arr[i] === value) {
      return i;
    } else {
      return -1;
    }
  }
}

For some reason it keeps returning -1 even if the value if found. What am I doing wrong?

CodePudding user response:

In the first time your if happen you return no matter what!

If arr[i] == value you return the index, else - you return -1.

What you want to do is return -1 in the case that none of the array elements is found.

function getIndex(arr, value) {
  for (let i = 0; i < arr.length; i  ) {
    if (arr[i] === value) {
      return i;
    }
  }
  return -1;
}

CodePudding user response:

Your logic is wrong here. First, you return -1 when the function fails to search the right value. Thus, the function is paused and no longer executing. You can learn more about the return statement at MDN. To solve this problem, you need to put the return statement outside the loop. Here is the working code:

<script>
function getIndex(arr, value){
for(let i =0; i<arr.length; i  ){
if(arr[i] === value){
return i;
}
}
return -1;
}
document.write(getIndex([1,2,3,4], 21));
</script>

The reason why this piece of code works is because when the value is found, it returns the positions where the value is. Thus, terminates the function. But if it is not, the loop will go forever until I is less than arr.length. Once I is less than arr.length, the loop is done and the return statement is executed.

  • Related