Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
Take input from user and verify if it is present in an array. (Javascript)

How can I take input from the user and check if the number is present in my array or not. I need to generate random number from array1 and move it to array2. Then I need to let the user input a number and check if the number is present in array2 or not. I already have the first part figured out but need help with the second part which is taking input and checking it against array2.

Here's what I have so far

const arr1 = [1,2,3,4,5,6]
const arr2 = []

const ran = () => {
  const index = Math.floor(Math.random() * arr1.length);
  if(arr1.length>0)
  {
    arr2.push(arr1[index])
    arr1.splice(index, 1)
    
    const display = document.getElementById('array')
    display.innerText = ("\nArray 2 elements " + arr2.toString() + "\n Remaining Array 1 elements" + arr1.toString())
  }
  else
    {
      document.write("Array is now empty");
    }
}
<button onClick=ran()>click</button>
<span id='array' />

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

For that, you can just get an input with your desired method (I've used an input element), change it to a number, and check if it's in array2:

const arr1 = [1,2,3,4,5,6]
const arr2 = []

const ran = () => {
  const index = Math.floor(Math.random() * arr1.length);
  if(arr1.length>0)
  {
    arr2.push(arr1[index])
    arr1.splice(index, 1)
    
    const display = document.getElementById('array')
    display.innerText = ("\nArray 2 elements " + arr2.toString() + "\n Remaining Array 1 elements" + arr1.toString())
  }
  else
    {
      document.write("Array is now empty");
    }
}

const checkUserInput = () => {
  let userInput = Number(document.getElementById("userInput").value);
  if (arr2.includes(userInput)) {
    console.log(`${userInput} in arr2`);
  } else console.log(`${userInput} not in arr2, at this time`);
  document.getElementById("userInput").value = "";
}
<button onClick=ran()>click</button>
<span id='array'></span>
<br>
<input type="text" id="userInput" placeholder="User input">
<button id="userInputCheck" onClick="checkUserInput()">Check Input</button>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda