+ 4
I am stuck at splice()
I want to make something that randomly chose an element of the array, use it somewhere, and after that delete that element. I want to do the same thing 6 times and there cannot be the same array element more than once. Help please... This is so confusing. I hope you understand. Sorry if not. 😅 https://code.sololearn.com/WlFxJl8VA8Dr/?ref=app
1 ответ
+ 2
var list=[1,2,3,4,5,6]
for(let i = 0; i < list.length; i++) {
let randomNum = Math.floor(Math.random() * list.length);
console.log(randomNum + " the random number")
console.log(list[randomNum] + " list element");
list.splice(randomNum, 1);
console.log(list + " list after splice")
}
You should use a loop, this code generates a random number and in every loop will remove one index in the array. Eventually it ends up with just a couple elements.