1

I am trying to check if a number entered exists in an array. I've tried many things and haven't got anything to work.

function start() {
    var arrNum = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
    var input = document.getElementById('input').value;
    var numberExist = document.getElementById('numberExist').innerHTML;

    for (var i = 0; i < arrNum.length; i++) {
        if (input === arrNum[i]) {
            alert('input');
            numberExist = ('The number ' + input + 'exists in the array');
        } else {
            numberExist = ('The number ' + input + 'does not exist in the array');
        }
    }

    var arrNum = arrNum.join(' ');
    document.getElementById('listOfvalues').innerHTML = ('The values in the array are ' + arrNum);
}
gyre
  • 16,369
  • 3
  • 37
  • 47
Ghrafkly
  • 105
  • 4
  • 12
  • 1
    Use in operator – Tilak Madichetti Apr 16 '17 at 06:20
  • Possible duplicate of [How do I check if an array includes an object in JavaScript?](http://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) the title might sounds wrong but it's exactly what you are looking for – caramba Apr 16 '17 at 06:21
  • Possible duplicate of [Which equals operator (== vs ===) should be used in JavaScript comparisons?](http://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons) –  Apr 16 '17 at 07:34

9 Answers9

1

Here are a few pointers:

  • You need to cast your input.value to an integer, e.g. using the unary + operator, because the HTMLInputElement#value property returns a string.
  • Your else block will run on the first for-loop iteration unless you move it outside of the loop body.

function start() {
  var arrNum = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20]
  var input = +document.getElementById('input').value
  var numberExist

  for (var i = 0; i < arrNum.length; i++) {
    if (input === arrNum[i]) {
      numberExist = 'The number ' + input + ' exists in the array'
    }
  }
  if (!numberExist) {
    numberExist = 'The number ' + input + ' does not exist in the array'
  }
  document.getElementById('listOfvalues').textContent =
    'The values in the array are ' + arrNum.join(' ')
  document.getElementById('numberExist').textContent = numberExist
}

start()
<input type="number" id="input" value="18">
<div id="listOfvalues"></div>
<div id="numberExist"></div>

Of course, as others have pointed out, this example can be greatly simplified using the Array#indexOf method:

function start() {
  var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20]
  var input = +document.getElementById('input').value
  var numberExist = array.indexOf(input) < 0
    ? 'The number ' + input + ' does not exist in the array'
    : 'The number ' + input + ' exists in the array'

  document.getElementById('listOfvalues').textContent =
    'The values in the array are ' + array.join(' ')
  document.getElementById('numberExist').textContent = numberExist
}

start()
<input type="number" id="input" value="18">
<div id="listOfvalues"></div>
<div id="numberExist"></div>
gyre
  • 16,369
  • 3
  • 37
  • 47
  • What is purpose of `var arrNum = arrNum.join(' ')` at first stacksnippets? – guest271314 Apr 16 '17 at 06:40
  • In OP's original code, I think the goal was to print the values of `arrNum` separated by spaces. The intermediate assignment to `arrNum` is unnecessary, though; I removed it in the second example but I see I forgot to do so in the first. Let me edit and combine a few lines. – gyre Apr 16 '17 at 06:45
0

Try indexOf function Eg:

arr = [1, 4, 18, 5, 10];
arr.indexOf(4); //returns 4
arr.indexOf(20); //returns -1
gaganshera
  • 2,629
  • 1
  • 14
  • 21
0

Use indexOf method

var arrNum = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];

function checkNumber(x){
 if(arrNum.indexOf(x)!=-1){
    alert('number exist')
 }
 else{
 alert('dont exist')
 }

}
checkNumber(8) // alert don't exist
brk
  • 48,835
  • 10
  • 56
  • 78
0

Array prototype has a method indexOf which returns the index of the element, if such exists, -1 otherwise.

In ES6 includes method is added, which returns true/false depending on element's existence.

Anoush Hakobyan
  • 1,255
  • 1
  • 11
  • 22
0

Try this:

function checkIfExists(arr, num){
  for (var i = 0; i < arr.length; i +=1){
      if(num === arr[i]){
        return true;
      }
  }
  return false;
}

var arrNum = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
var userInput = document.getElementById('user-input');

arrNumStr = arrNum.join(",");
    document.getElementById('listOfvalues').innerHTML = ('The values in the array are ' + arrNumStr);
    
document.getElementById('check').onclick = function  () {
var input = Number(userInput.value); // Using Number to convert from string to number
    
    //if (arrNum.indexOf(input) > -1)
    if (checkIfExists(arrNum,input)){
        alert('Number is exists')
    }else{
        alert('Number not exists');
    }
  
}
<input type="text" id="user-input">
<br>
<input type="button" id="check" value="Check">
<br>
<div id="listOfvalues" ></div>
Mohamed Abbas
  • 2,228
  • 1
  • 11
  • 19
0

convert input value to number which is by default string.

var input = +document.getElementById('input').value;
//OR input = Number(document.getElementById('input').value);
//OR input = parseInt(document.getElementById('input').value, 10);

break the loop if number is found, do not continue running the loop.

if (input === arrNum[i]) {
        numberExist.innerHTML = ('The number ' + input + ' exists in the array');
        break;
    }

window.onload = start;
function start() {
    var arrNum = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
    var input = +document.getElementById('input').value;
    var numberExist = document.getElementById('numberExist');

    for (var i = 0; i < arrNum.length; i++) {
        if (input === arrNum[i]) {
            numberExist.innerHTML = ('The number ' + input + ' exists in the array');
            break;
        } else {
            numberExist.innerHTML = ('The number ' + input + ' does not exist in the array');
        }
    }

    var arrNum = arrNum.join(' ');
    document.getElementById('listOfValues').innerHTML = ('The values in the array are ' + arrNum);
}
<input type="number" id="input" value="18" onblur="start()"/>
<button onclick="start()">Check</button>
<div id="numberExist"></div>
<div id="listOfValues"></div>
sabithpocker
  • 15,274
  • 1
  • 42
  • 75
0

Strict equality operator compares types: Which equals operator (== vs ===) should be used in JavaScript comparisons?.

console.log("1 == 1 is", 1 == 1);
console.log("1 == \"1\" is", 1 == "1");
console.log("1 === 1 is", 1 === 1);
console.log("1 === \"1\" is", 1 === "1");
console.log("1 === parseInt(\"1\", 10) is", 1 === parseInt("1", 10));
Community
  • 1
  • 1
0

This can now be done with the 'includes' method (not in Edge 13 or earlier).

if( arr.includes(valueToFind) ){

w3schools

Shawn
  • 3,031
  • 4
  • 26
  • 53
-1

Try to use Number() function. Such as Number(input). Since you input box type is not Number. Thus in input variable you are always getting string. Thus you need to convert the string to numeric.

Akhter Al Amin
  • 852
  • 1
  • 11
  • 25