0

how to search the value in te array using loops.. not able to sort out the value what's wrong in this solutions ...

function arrayCheck(arr, value) {
  var arr = [35, 56, 78, 90, 54];
  for (var i = 0; i < arr.length; i++) {
    // var value = arr.length;

    if (arr[i] === value) {
      return i;
    } else {
      return "Not found";
    }
  }
}

// // arraycheck(value);
console.log(arrayCheck(56));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
khawar shah
  • 311
  • 2
  • 3
  • 10
  • 4
    `return` will quit your function, so your for loop will stop running and "Not found" will be returned as soon as any item does not equal the input `value` – Nick Parsons Jan 26 '21 at 12:31
  • 3
    There are about a dozen duplicates for this...off to find one. *(Edit: Meh, I need to get back to work and people insist on posting duplicate answers anyway.)* – T.J. Crowder Jan 26 '21 at 12:31
  • 1
    Move the `return "not found"` below the `for` loop (and you really shouldn't mix the type of the return value. Always return a number, a boolean, a string, ... but not one or the other) – Andreas Jan 26 '21 at 12:32
  • Not a real dupelicate, but... [Does return stop a loop?](https://stackoverflow.com/questions/11714503/does-return-stop-a-loop) – Andreas Jan 26 '21 at 12:36

1 Answers1

1

The function expects 2 arguments - arr and value. You pass the value (56) in place of the arr.

In addition, returning in the else means that if the 1st item is not the requested value, the iteration would stop, and return "Not Found".

Pass the array to the function, and return "Not Found" after the loop ends:

function arrayCheck(arr, value) { 
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === value) {
      return i;
    }
  }
  
  return "Not found";
}

var arr = [35, 56, 78, 90, 54];

console.log(arrayCheck(arr, 56));

A simpler solution would be to use Array.indexOf():

const arrayCheck = (arr, value) => {
  const idx = arr.indexOf(value);
  
  return idx === -1 ? "Not found" : idx;
};

const arr = [35, 56, 78, 90, 54];

console.log(arrayCheck(arr, 56));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209