Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a specific character from array in JS?

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; 
}
like image 891
Arex Speed Avatar asked Dec 11 '25 20:12

Arex Speed


1 Answers

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);   
like image 169
Maheer Ali Avatar answered Dec 14 '25 10:12

Maheer Ali