'Move elements from one array to another and display value of both arrays at the same time
(Javascript) How do I move elements from one array to another in random order on click of a button and also display elements in both the arrays at the same time?
For example the desired output is :
Elements in array1 : 1,2,3,4,5
Elements in array2 : -
BUTTON
now on clicking the button
Elements in array1 : 1,2,4,5
Elements in array2 : 3
BUTTON
now on clicking the button
Elements in array1 : 2,4,5
Elements in array2 : 3,1
BUTTON
now on clicking the button
Elements in array1 : 2,5
Elements in array2 : 3,1,4
BUTTON
and so on...
This is what i got from another stackoverflow user.
let array1 = [1, 2, 3, 4, 5]
document.getElementById("btn").onclick = () => {
let num = array1[Math.floor(Math.random()*array1.length)]
const index = array1.indexOf(num);
if (index > -1) {
array1.splice(index, 1);
alert("You chose: " + num + "\nArray: " + array1)
} else {
alert("No numbers remaining.")
}
}
<button id="btn">Get Random Number</button>
Solution 1:[1]
I think you were basically there. The below gets an element in the dom via ID and sets the text value to the array you're adding to. You can run the code snippet below to see what's going on. Good luck ?!
const arr1 = [1,2,3,4,5,6]
const arr2 = []
const doThing = () => {
// get the random position
const index = Math.floor(Math.random() * arr1.length);
// push the random index to the second array
arr2.push(arr1[index])
// remove the randome index from arr1
arr1.splice(index, 1)
// show it
const display = document.getElementById('array')
display.innerText = arr2.toString()
// log both out so you can see what's happening
console.log(arr1, arr2)
}
<button onClick=doThing()>clicky</button>
<span id='array' />
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 | sesamechicken |
