How can I remove a special number from array in this example. I have 9 numbers in array nums and empty array narr. I want to delete a random index (let rand) from nums and add this to narr. In narr pushing is correct but when i tried delete the same number from nums by pop, splice, slice etc it didn't correct answer. Which metod should i use?
function sudoku(arr){
let nums = [1,2,3,4,5,6,7,8,9];
let narr = [];
for(let i = 0; i<9; i++){
let rand = Math.floor(Math.random()*nums.length);
narr.push(nums[rand]);
nums.pop(nums[rand]);
}
return narr;
}
You should use splice() to remove the element from array. pop() removes last element. If you want to remove an element from index rand you can use splice()
The first argument of splice() is the index from which you want to remove element and second argument is no of elements you want to remove
nums.splice(rand, 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With