Slicing not working to remove an element from array

const arr=[ [ ], [ ], [ ] , [ ] , [ ] , [ ] , [ ]  ]
// after some insertions my array looks like arr : [a , b] , [   ] ,  [    ]  ............
                            for(let i = 0; i < arr.length ; i++)
                              if(arr[position][i] == selected_option) // is true for this case
                               console.log(arr[0][0]);     // prints a  
                               console.log(arr[0][1]);     // prints b 

                               arr[0].splice(1,1);         // does not remove "b" from array
                                arr.splice(i, 1);          // this syntax also does not removes "b" from array 

Its not deleting the index whose value is b! Please help

One of the issues that I see there is that your loop is for the array length, but then with arr[position][i] you are indexing by position.

Shouldn’t you be indexing by arr[i] instead of by arr[position]?

You’re trying to manipulate array while iterating it - thats wrong. If you delete array items inside the loop, array length changes but loop continues to go for original array length.

Instead of deleting items inside the loop, keep their indexes in another array and then use second loop to delete them

Well, it’s technically not “wrong” to manipulate the array while iterating it, you just have to be careful doing so.

This looks more a case for map than a walking splice loop… what’s your intended input/output?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.