Lars Antonsen Lars Antonsen - 1 month ago 6
HTML Question

Trying to find if a number exists in my array through input

I am trying to find a number by using the input to search in the array.
Got any idea why this does not work?

Every time i run the code i only get the message:


"Number does not exist"


var arr = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];

var number = document.getElementById("find").value;

var svar = "";

function exists(){

for(i=0; i < arr.length; i++){
if(parseInt(arr[i]) == parseInt(number)){
svar++;
document.getElementById("existsArray").innerHTML = tall + "Number exists";

} else {
document.getElementById("existsArray").innerHTML = tall + "Number does not exist";
}
}
}

<p id="existsArray"></p>
<input placeholder="what number would you like to find?" id="find" type="number">
<button type="button" onclick="exists()">Finn tallet</button>

Answer

I replaced your for loop with indexOf

If you still want to use the loop you should break when you find the matching number

var arr = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];
var svar = 0;

function exists() {
  var number = +document.getElementById("find").value;
  if (arr.indexOf(number) !== -1) {
    svar++;
    document.getElementById("existsArray").innerHTML = "Number exists";
  } else {
    document.getElementById("existsArray").innerHTML = "Number does not exist";
  }
}
<input type="number" id="find" />
<button onclick="exists();">Does it exist ?</button>
<p id="existsArray"></p>

If you want to get the number of occurrence you should use this :

var occurrences = arr.filter(function (num) {return num === number;}).length