Madhavee
Madhavee

Reputation: 67

Check if value exists in JavaScript array

I have the following code snippet.

$scope.functionName = function(id) {
  var flag = true;
  var numbers = [1, 3, 30];

  for (var i = 0; i < numbers.length; i++) {
    if (id == numbers[i]) {
      flag = false;
    } else {
      flag = true;
    }
  }
  if (flag == true) {
    console.log("this is true");
  }
  if (flag == false) {
    console.log("this is true");
  }

}

What I want to perform is, if the input value is in the array, flag value should be false and if not it should be true. But, in this code snippet although flow goes inside the for loop after that it doesn't go to any of the if conditions. After entering the for loop it directly outputs "this is true". flag is always being true.

Upvotes: 1

Views: 114

Answers (3)

Majedur
Majedur

Reputation: 3242

Add a break statement when your value equal to a value in array.

 $scope.functionName = function(id) {
      var flag = true;
      var numbers = [1, 3, 30];

      for (var i = 0; i < numbers.length; i++) {
        if (id == numbers[i]) {
          flag = false;
          break;
        } 
      }
      if (flag == true) {
        console.log("this is true");
      }
      if (flag == false) {
        console.log("this is false");
      }

    }

Upvotes: 0

Lelouch
Lelouch

Reputation: 970

here is a cleaner approach at what you are trying to achieve

checkIfNumberIsInArray = function(number, arr) {
  return arr.includes(number)
}

console.log(checkIfNumberIsInArray(1, [1,2,3,4,5])) // true
console.log(checkIfNumberIsInArray(6, [1,2,3,4,5])) // false

See MDN JavaScript Reference - array.includes

Upvotes: 2

SkarXa
SkarXa

Reputation: 1194

You don't need to loop the array, just use indexOf. Also try to use number type for numbers, and boolean type for booleans, you are using string for both

$scope.functionName = function(id)
{
    var numbers = [1, 3, 30];

    var flag = numbers.indexOf(parseInt(id, 10)) > -1;  // Convert to number just in case

    if(flag === true)
    {
        console.log("this is true");
    }
    if(flag === false)
    {
        console.log("this is true");
    }
}

Upvotes: -1

Related Questions