Iterate Through All an Array& Items Using For Loops

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++){
      if(arr[i][j]==elem){
       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:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops

1 Like

where did i go wrong?

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

    }
  }
 
4 Likes

how can do this? i don’t understand…

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

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:

You have to declare i with either var or let

for(let i=0; i<arr.length; i++) {

Hi, i added some comments here to give you an idea how this is working

function filteredArray(arr, elem) {
  let newArr = [];
  // first the for loop for length definition
  for (let i = 0; i < arr.length; i++) {
    // now the if clause to check if there is something ther if there is nothing you should add the array, this is the reason why we use -1 here
    if (arr[i].indexOf(elem) === -1) {
      // push it to the array
      newArr.push(arr[i]);
    };
  };
  // return the newArr to make it available outside the function
  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));

All the best and looking forward to hear from you soon
cheers Mchoeti

1 Like

Thank you soo much! This is much easier to comprehend than the nested for loops in the original solution.