'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' />
Solution 1:[1]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jsN00b |
