Iterate Through All an Array's Items Using For Loops helpp

should i create a nested for loop to access items inside the nested array?

Your code so far


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]);
   
  }
}
  // 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 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 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

Yes a nested for loop is one way of getting to the individual values of each array. There are other ways as well of doing that if your objective is to check a condition for eg, But understanding how to write a nested for loop is important so go for that now.

for (let  i = 0;i < arr.length;i++){
  for(let j = 0;j < arr[i].length;j++){
   if (arr[i].indexOf(elem) != -1){
      newArr.push(arr[i]);
   
  }  
  }
   
}

what am i dping wrong here

I think the index j should appear somewhere in your “if” statement.

i have to check if the element is there inside the nested array,if i use the index j in the if statement it will check for the element inside the element

Here is my suggestion for your “if” Statement

if (arr[i].indexOf(elem) == -1){
      newArr.push(arr[i]);
}

That will suffice to make your first code work, I believe.

if you will use indexOf to check each array, then you don’t need the 2nd for loop.

(because indexOf works over the entire array and doesn’t need your help to do that)