Iterate Through All an Array& Items Using For Loops

Iterate Through All an Array& Items Using For Loops
0.0 0


Tell us what’s happening:

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++){
       delete arr[i];
       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));

Your browser information:

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

Link to the challenge:


where did i go wrong?


The above line mutates arr, so the length is changes, so you have to account for the change in the inner for loop, because if not, you are going to get the error TypeError: Cannot read property ‘length’ of undefined on the next iteration after the deletion.

I recommend creating a new array of the filtered elements instead of deleting elements out of the original array.


ok , let me try this again. Thank you!


Your thinking is perfectly valid but it helps even more if you know some of the built-in functions to make it considerably shorter. At first, it was tempting for me too to use your approach, but after some thinking, see below for the much shorter and compact solution:

  for (let i=0; i<arr.length; i++)
  if (arr[i].indexOf(elem)< 0)



how can do this? i don’t understand…


What exactly are you asking? If you are having trouble with code for a challenge, use the Ask for Help button on the challenge and ask a question.


thx .
i just can’t understand @coderF’s code, and now ,i think i get it .


Anyone know why the following code works in the google developer console, but shows ‘i is not defined’ errors in code camp?
for(i = 0; i < arr.length ; i ++){
if (arr[i].indexOf(elem) === -1){

Solved: If anyone was wondering - i didn’t initiate the variable ‘i’ properly. I put ‘let’ at the front and it worked.

Doh! Learned something though :slight_smile: