Iterate Through All an Array's Items Using For Loops wiht if else statements?

Tell us what’s happening:
hey guys, help would be greatly appreciated. I know that in this challenge you can also use indexOf, but i didn’t think of it and wanted to know if this is a possibility, although my syntax is off somewhere i can not manage to make it work.

Your code so far


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

// change code here to test different cases:
console.log(filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:69.0) Gecko/20100101 Firefox/69.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

Can you break down what this is doing, It can be simplified quite a bit.

Also, you probably shouldn’t mutate the array that the for loop is working on. that’s where the main bug is originating. all you actually need to do is remove the line where you are splicing the ‘arr’ and it works.

The for loop is checking arr.length after each iteration. When you splice the array, it mutates it, changing arr.length.

You can also use the array.filter and array.include methods. Pairing these with arrow functions makes it super readable imo. Here’s another way to write the same function, it doesn’t use a for loop, but achieves the same thing.

const filteredArray = (arr,elem) => arr.filter(subArr => !subArr.includes(elem))

wow great, i didnt realize i was mutating the original array, an all i needed to do was not splice. thanks so much for the reply. all the other info is greatly appreciated and i will check every solution possible.
The first part was checking if that element was inside the array, but in the execution of copying the result is where i got a bit lost.