3

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; 
}

1 Answer 1

3

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);   
Sign up to request clarification or add additional context in comments.

1 Comment

@ArexSpeed Accept the answer if you think it solved your problem. If you have any problem you can ask

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.