Comparing a key in an array

I have an array

frontAssets

I want to create a function to see see if the value of a text box is greater or less than 1 key in a array

 function detectCollision() {
      
        var selectValue	= document.getElementById("Beginning_ru").value;

        frontAssets.forEach((asset) => {
            
           if(selectValue > asset['beginning_ru']) {

            window.open('#Collision');

      }
    }                                           

Would this send the user to the Collision target if the selectValue is greater than the key in any index in my arhray?

No it will open a new window for each array entry which matches this criteria

If you’re trying to move the user’s vision on the same page, you’re looking for scrollIntoView

1 Like

Instead of forEach, you could use Array.some

So maybe something like this

function detectCollision(assets = []) {    
  const selectValue	= document.getElementById('Beginning_ru').value;
  const target = document.getElementById('Collision')

  // Array.some. 
  // If a match is found, returns early with true
  // Otherwise returns false
  if (assets.some((asset) => selectValue > asset['beginning_ru'])) {
    target.scrollIntoView()
  }
}

detectCollision(frontAssets)

or alternatively

// just have the function return true or false
function detectCollision(assets = []) {    
  const selectValue	= document.getElementById('Beginning_ru').value;

  return assets.some((asset) => selectValue > asset['beginning_ru'])
}


if (detectCollision(frontAssets)) {
  document.getElementById('Collision').scrollIntoView()
}
3 Likes

the second one seems good
I want the function to run when a form is submitted though

<form...  onSubmit="detectCollision(frontAssets)">
...
</form>
...
// just have the function return true or false
function detectCollision(assets = []) {    
  const selectValue	= document.getElementById('Beginning_ru').value;

  return assets.some((asset) => selectValue > asset['beginning_ru'])
}

if (detectCollision(frontAssets)) {
  document.getElementById('Collision').scrollIntoView()
}

Should I put the if statement inside the function?

I also think that this 2 will be correct, it would be nice if someone else spoke up

That wasn’t the intention, no.

Personally I prefer to try and keep functions to one task. The function is called ‘detect’, so I would expect it to return something. The action of scrolling in my mind is separate to that.

Maybe I am complicating things, and the first version might be an easier choice.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.