1

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>
4
  • 3
    You need to break once you find the matching element. You are still running through the array so it won't work unless the last element in your array is the one that matches. Commented Oct 11, 2016 at 13:52
  • what is tall and why do you have svar Commented Oct 11, 2016 at 13:55
  • 1
    Also, a couple of notes: Since your array contains numbers already you don't need to parseInt them. Also, since number isn't going to change in the loop, you only need to parseInt it once and then use that value in the loop. Lastly you could use Array.prototype.find or Array.prototype.indexOf to make this much simpler. Commented Oct 11, 2016 at 13:55
  • Sorry, tried to translate my code before posting it. Missed a few. Tall is supposed to be number, and svar was supposed to hold the number if it found a matching one. Commented Oct 11, 2016 at 13:57

4 Answers 4

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! That was alot easier then the for for loop.
I have to ask. If i want to find out how many times the number i put in the ìnput` exists in the array. What do i need to add to the existing code?
0

So your problem is that you don't exit the loop when you find the matching number. As a result, unless the number you are looking for is the very last number in your array, it will keep looping and the else clause will execute.

function exist() {
    var number = parseInt(document.getElementById("find").value,10);
    for(i=0; i < arr.length; i++){ 
         if (exists === arr[i]) {
              // number exists
              break;    // <-- this is important another alternative would be to just 
                        // return at this point if the function doesn't do anything else
         }
         else {
              // this number doesn't match, so we'll keep searching
         }
    }
}

Of course, this is much easier if you just use the built in functions Array.prototype.find or Array.prototype.indexOf

Comments

0

You can also use a filter to keep only values in the array wich match with input :

var arr = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];
var input = "65";
var result = arr.filter(item => item === parseInt(input));
if (result.length === 0) console.log("number doesn't exist");
else console.log("number exists");

Comments

0

I've made some modifications to your code up front to help isolate your test case. If you look at this rework of your existing code, you'll see you get a message for each of your array elements, ending with "Number does not exist", which was your original problem. This is because that's the last message, overwriting your previous positive results.

var number = "42";
//var svar = "";
var svar = 0;//changing this from a string to a number. Can't ++ a string.
var myArray = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];
/* 
 * @param {String} num - Passing the value that I'm looking for, rather than 
 *    trying to pull it from elsewhere. This makes this much easier to test later.
 * @param {Array} arr - Array of integers to search
 */
function exists(num, arr) {
  for(i=0; i < arr.length; i++){
    //if(parseInt(arr[i]) == parseInt(number)){
    //No need to use parseInt here on the array. It's already a Number.
    if(arr[i] == parseInt(number)){
      svar++;/* I don't see any reason to be incrementing this. Perhaps it's elsewhere
          in your implementation? */
      //Using console.log() instead of elements not included in your code sample
      console.log("Number exists");
    } else {
      //This keeps overwriting the above, except in a case where
      //the last number would be a match!
      console.error("Number does not exist");
    }
  }
}

exists(number, myArray);

If you want this to work as intended, you can either can eliminate your "Number does not exist" else branch, which will cause the positive message to remain, and you can leave your default text as "Number does not exist", or you simplify it, using what I'd recommend:

var number = "42",
    number2 = "101",
    myArray = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];

var existsSimple = function (num, arr) {
  return myArray.filter(function (itemNum) {return itemNum === parseInt(num);}).length > 0;
};

console.log('Number exists: ' + existsSimple(number, myArray));//true
console.log('Number exists: ' + existsSimple(number2, myArray));//false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.