HELP----Iterate Through All an Arrays Items Using For Loops

Tell us what’s happening:
so the question is–We have defined a function, filteredArray, which takes arr, a nested array, and elem as arguments, and returns a new array. elem represents an element that may or may not be present on one or more of the arrays nested within arr. Modify the function, using a for loop, to return a filtered version of the passed array such that any array nested within arr containing elem has been removed.

What I am doing is a for lope which enters the array through i and to move inside that array I am using j, if in ith array jth element gets equal to element then delete that array and break the j loop so that value of i can be changed, but it is showing errors, WHere am I wrong, please Help,
Thank You

Your code so far


function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
  for(let i=0;i<arr.lenght;i++){
    for(let j=0;j<3;j++){
      if(arr[i][j]==elem){
         arr.splice(i,1);
         console.log(arr);
         break;
      }
    }
  }
  return arr;
  // change code above this line
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0.

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

This is a typo: i<arr.lenght

After that you have a problem in the if statement too: when you use splice the index of all the other elements will be reduced by one, it means you can’t delete two inner arrays one following the other ^^

Thank You @Layer I have made the corrections and got to learn some more things.

1 Like

Also in this exercise you are requested to return the newArr. Also with the function myArr.indexOf(whatYouAreLookingFor), you don’t need to loop inside your nested array.

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

Hello DwightMint, The main problem which I found was first that layer mentioned i.e spelling error, second is as I am removing elements from the initials index all the index of other elements changes hence I must delete from the last of the array. This solution was suggested by @Christinakal,

Thank You