Iterate Through All an Array's Items Using For Loops, it's seems logical but doesn't work?

Hi everyone

I’m struggling with this challenge my solution seems to be logical but doesn’t work

could anyone of you explain where is the problem, please?

here is the code


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

The challenge expects you to only include any given sub array if none of the elements matches the elem value.

You have two issues:

  1. You are checking if each sub array element is not equal elem and for any which are not equal, you are adding the element to newArr.
  2. You should be pushing arrays (sub arrays of arr) to newArr instead of individual sub array elements.
1 Like

I’ve no idea on how to do it or correct those mistakes you mentioned here I try this based on your advice but I think not this way, here my new solution!?


function filteredArray(arr, elem) {
  let newArr = [];
  for(let i = 0; i < arr.length; i++){ 
    for(let j = 0; j < arr[i].length; j++){ 
      if(arr[i][j] != elem){
        newArr.push(arr[i])
        }
     }
    
  }
  // change code above this line
  return newArr;
}
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

You need to fully check the inner array before you can make the decision to push it or not. One simple way might be to keep a count and test against it before pushing.

Or look into some array methods, see if you can find one that might be useful (one of them has a name that might be a giveaway)