0

I need to return the index place of my target and if my target is not present in my nums array I need to return -1. When I run my code it is like only my second return works?

function search(nums, target) {
    for (let i = 0; i < nums.length; i++) {
        let exist = nums[i]
        if (exist == target) {
            return [nums.indexOf(exist)]
        } else {
            return -1
        }
    }
}

console.log(search([-1, 0, 3, 5, 9, 12], 9))
0009laH
  • 1,960
  • 13
  • 27
  • 2
    Move the second return statement outside the loop. – Spectric Jan 31 '23 at 19:50
  • 1
    Why are you reinventing indexOf in a for loop? `function search(nums,target) { return nums.indexOf(target); }` – epascarello Jan 31 '23 at 19:51
  • 2
    Just `return nums.indexOf(target);`, no loop needed. – Teemu Jan 31 '23 at 19:51
  • Does this answer your question? [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript) – ThisaruG Feb 01 '23 at 11:07

1 Answers1

0

You need to move the return -1 statement outside of the for loop

try this

function search(nums, target) {
  for (let i = 0; i < nums.length; i++) {
    let exist = nums[i];
    if (exist == target) {
      return i;
    }
  }
  return -1;
}

console.log(search([-1, 0, 3, 5, 9, 12], 9));
epascarello
  • 204,599
  • 20
  • 195
  • 236
Yacine
  • 286
  • 2
  • 6