Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is find() not returning correct value?

I´m trying that when a value that is not in the array is introduced, it shows in the screen. So, when the find method doesn´t return undefined, it shows the value that has been introduced. But I don´t know why, it always return undefined.

Code:

<html>
<body>

<p id="demo"></p>

<input type="text" id="number">

    <script>
      var number = document.getElementById("number");

      const array1 = [5, 12, 8, 98, 44];

      var found = array1.find(element => element == number.value);

      number.addEventListener("input", function(){
        if(found == undefined){
          document.getElementById("demo").innerHTML = number.value;
        }
      });
  </script>
</body>
</html>
like image 229
d1845412 Avatar asked May 22 '26 11:05

d1845412


1 Answers

You need to take the actual value from input in the event function as well as the find method. Otherwise you get the initial value from the input and the result of a find which does not match later inputs.

You could take Array#some instead of Array#find, because you have just numbers in the array. If you would have object and need one, find would work better here, because you get a different result than a simple number.

A word to Equality operator ==. This operator should be avoided, because it changes the type fo comparing with another value. Instead use Identity/strict equality operator ===, which checks the type and value.

const array1 = [5, 12, 8, 98, 44];

number.addEventListener("input", function() {
    var number = document.getElementById("number"),
        found = array1.some(element => element == number.value);

    if (found) {
        document.getElementById("demo").innerHTML = 'found';
    } else {
        document.getElementById("demo").innerHTML = 'not found: ' + number.value;
    }
});
<p id="demo"></p>
<input type="text" id="number">

For a smarter approach take Array#includes` as check with a value as number as parameter.

const array1 = [5, 12, 8, 98, 44];

number.addEventListener("input", function() {
    var number = document.getElementById("number").value;

    if (array1.includes(+number)) {
        document.getElementById("demo").innerHTML = 'found';
    } else {
        document.getElementById("demo").innerHTML = 'not found: ' + number;
    }
});
<p id="demo"></p>
<input type="text" id="number">
like image 176
Nina Scholz Avatar answered May 23 '26 23:05

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!