Trying to recreate indexOf method in JavaScript

274 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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));

0
On

It will works the same as method IndexOf

numbers.indexOf = function(value, indexFrom = 0) {
  const count = this.length;
  let fromIndex = indexFrom;

  if (fromIndex < -count + 1) {
    fromIndex = 0;
  }

  if (fromIndex < 0) {
    fromIndex += count;
  }

  for (let i = fromIndex; i < count; i++) {
    if (this[i] === value) {
      return i;
    }
  }

  return -1;
};