javascriptindexofrecreate

Trying to recreate indexOf method in JavaScript


I'm trying to recreate the indexOf array method in JavaScript. For the life of me, I can't figure out why the following isn't working:

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

For example:

indexOf([1,2,1,3], 2) // should return 1

Thanks in advance.


Solution

  • You just need to move the return -1 outside of your for loop.

    function indexOf(array, value) {
        for (let i = 0; i < array.length; i++) {
            if (array[i] === value) {
                return i;
            }
        }
    
        return -1;
    }
    
    console.log(indexOf([1, 2, 1, 3], 2));
    console.log(indexOf([1, 2, 1, 3], 4));