user11341542
user11341542

Reputation:

How to iterate over any array to return the value "true" if any elements are true

This question is regarding JavaScript. If the input is any of the following array "hello, hi, yo, or hey", I want the value to return true, but it is only returning false.

I've tried multiple methods like toString(), includes(), etc.

function myFunction() {
  var arr1 = [/hello/i, /\bhi/i, /\bhey/i, /\byo\s/i];
  var b = document.getElementById("input1").value;
  for (i = 0; i < arr1.length; i++) {
    var greeting1 = arr1[i].test(b);
    greeting1.toString()
    document.getElementById("demo").innerHTML = greeting1
  }
}
<input type="text" id="input1">
<button type="submit" onclick="myFunction()">Test</button>
<p id="demo"></p>

I want the value to return true.

Upvotes: 2

Views: 73

Answers (2)

Shidersz
Shidersz

Reputation: 17190

One solution is to break the loop once a regular expression test() returns true:

function myFunction()
{
    var arr1 = [/hello/i, /\bhi/i, /\bhey/i, /\byo\s/i];
    var b = document.getElementById("input1").value;
    var res = false;

    for (i = 0; i < arr1.length; i++)
    {
        res = arr1[i].test(b);

        if (res)
            break;
    }

    document.getElementById("demo").innerHTML = res;
}
<input type="text" id="input1">
<button type="submit" onclick="myFunction()">Test</button>
<p id="demo"></p>

However, you can use Array.some() to simplify your code:

function myFunction() {
  var arr1 = [/hello/i, /\bhi/i, /\bhey/i, /\byo\s/i];
  var b = document.getElementById("input1").value;
  document.getElementById("demo").innerHTML = arr1.some(regexp => regexp.test(b));
}
<input type="text" id="input1">
<button type="submit" onclick="myFunction()">Test</button>
<p id="demo"></p>

Upvotes: 2

f-CJ
f-CJ

Reputation: 4481

You could use Array.prototype.some() to check if at least one of the regular expressions match. I've modified a little bit your code just to give you an example:

function myFunction(value) {
    var arr1 = [/hello/i, /\bhi/i, /\bhey/i, /\byo\s/i];
    console.log(arr1.some(a => a.test(value)));        
}

myFunction('hello');

The problem in your code is that you are overriding the text with the result of each iteration of the for loop.

Upvotes: 3

Related Questions