Is there any way to use splice() with a multidimensional array

Is there any way to use splice() with a multidimensional array
0

#1

Here’s my code {I know that’s not how you should use splice}

function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
  for(var i=0; i<arr.length; i++){
    if(arr[i].indexOf(elem) === -1){
      for(var j=0; j<arr[i].length; j++){
        if(arr[i][j] === elem){
          arr.splice((i,j), 1);
        }
      }
      newArr.push(arr[i]);
    }
    else{
      newArr.push(arr[i]);
    }
  }
  // change code above this line
  return newArr;
}

From lesson:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops


#2

In what way would you like to use splice with the multi-dimensional array?

Specifically, what are you hoping to achieve with the following?

arr.splice((i,j), 1);

#3

I wanted with this imaginary formula to remove an element from this position of i and j


#4

If you wanted to remove a specific element of a nested array in a two-dimensional array, then you would write:

arr[i].splice(j, 1);  // assumes i is index of the the nested array and j is the index of the element in the nested array you want to remove.

#5

But this way it’s going to remove a single item only and since they’re multiple arrays with the possibility that each array has multiple occurrences of this same character. So, that’s why I needed the nested for loops


#6

You are correct that the line above would remove a single element of a nested array (based on your original code). I was merely answering your question of the proper syntax to use to accomplish what you requested. The line I provided above assumes you are properly adjusting the j index value after a splice is made. For example, if j was 1 and you removed the element at index 1, then you would need to make sure you do not increment j in the inner for loop, because it would skip an element.


#7

I fully understand now, thanks for the time you’ve spent answering me :smile: