Removing a specific element from nested arrays

So I thought I had this challenge sorted, quite a good one.

I believe I used a nested for loop properly so each element inside every array inside the outer array is checked.

Your code so far




function filteredArray(arr, elem) {
  let newArr = [];

for ( var row = 0 ; row < arr.length ; row ++ ) {
  for (var col = 0; col< arr[row].length; col++) {

    if (arr[row][col] == elem) {

      delete arr[row][col];

    }

  }
}

newArr = arr;

  // change code above this line
  return newArr;
}

// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops

so

 if (arr[row][col] == elem) {

      delete arr[row][col];
}

is using delete a legit way of getting rid of elem = 3 if it exists in any of the arrays?
Would be great if .pop() was able to specify what to remove but alas it can only remove the last element of an array.

I also think

newArr = arr;

may not be in the correct position.

Please give some pointers if I’m anywhere close - or not. Thansk in advance

delete removes properties from objects. It’s not what you want to use to remove an element from an array.

Ah…

It must be splice() that should be in the if statement then?

That’d be the usual way to do it :slight_smile:

So I think…

arr[row].splice(0, b);

Now, the question is - how to determine what b is here? The elem=3’s position is not fixed and is different for each of the nested arrays…

Would this work?

   const elemLocation = arr[row].indexOf(elem);
     arr[row].splice(elemLocation,1);

Try it out and see if it does what you expect :smiley: