HELP: Iterate Through All an Arrays Items Using For Loops

Hi there,

I need advise on how to proper delete nested array based on elem, I cant get the logic to work properly, and am stuck on this for several days now… my code is as follows:

function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
    for (let i = 0; i < arr.length; i++){
    let arrLength = arr[i];
      for (let j = 0; j < arrLength.length; j++){
        if ( arrLength[j] === elem) {
          newArr = arr.splice(0, 1); 
        }
      }
    }   
  // change code above this line
  return newArr;
}
// change code here to test different cases:
console.log(filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2));

If I understand correctly with the code above I’m always deleting the zeroth index of the arr parameter if condition is met in inner loop…

I know that with splice original arr gets modified…

And in this case the code runs OK, but with different arguments, its not working as expected…

I don’t want working code, as I’d like to figure it out on my own… I would appreciate if you can give me some hints/advice on how to target the inner array which needs to be deleted.

Thank you

Hi Randell,

Thanks for the prompt answer… your suggestions helped a lot, and after few tests and tweaks I finally figured it out :grinning:

here is my working code:

function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
  
    for (let i = 0; i < arr.length; i++){
    let subArr = arr[i];
      innerLoop:
      for (let j = 0; j < subArr.length; j++){
        if ( subArr[j] === elem) {
          newArr = arr.splice(i, 1); 
          --i;
          break innerLoop;

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

Once again THANK YOU!!

Thank you :slight_smile:

I have updated my code as suggested, makes much more sense now :wink: