Iterate Through All an Array's Items Using For Loops help pls

Tell us what’s happening:

Hey could you explain why does my code not work? I cant come up with an idea to solve it… :frowning:

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) {
      arr[i].splice(i, 1);          
      } 
     }   
       newArr.push(arr[i]); 
    }  
    

  // 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));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36.

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/

Consider a slightly different approach, perhaps. Yes, use that outer for loop, to iterate over each sub-array, but is there a way to see if a given element exists in an array WITHOUT having to loop over that whole array? Hint, take a look at indexOf(…).

Inside your i loop, consider simply checking if elem is in arr[i]. If it is NOT, then push arr[i] onto your newArr.

Here’s the tricky bit – how do you check for the non-existence of elem in arr[i], in a single statement?

1 Like

Hey, first of all thanks for help.

I edited my code to look like this:


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

  // 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));

1 Like

Word of advice, though – when you post a working solution, wrap it in a spoiler tag (found under the gear menu, for this reply editor).