QP School

Full Version: JavaScript Array findIndex() examples (returns the index)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The HTML part between the <body></body> tags looks like this:

Code:
<h2>Example 1</h2>
<p id="demo"></p>
<h2>Example 2</h2>
<p>Click "Test" to return the index of the first array element that has a value above this number:</p>
<p><input type="number" id="toCheck" value="18"></p>
<button onclick="myFunction()">Test</button>
<p id="demo2"></p>


The JavaScript part looks like this:

Code:
// Example 1

const ages = [3, 10, 18, 20];

function checkAge(age)
{
  return age > 18;
}

document.getElementById("demo").innerHTML = ages.findIndex(checkAge);

// Example 2

const numbers = [4, 12, 16, 20];

function checkValue(x)
{
  return x > document.getElementById("toCheck").value;
}

function myFunction()
{
  document.getElementById("demo2").innerHTML = numbers.findIndex(checkValue);
}