How to remove sub arrays with 3 as element

  **Your code so far**

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

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
1 Like

Hello!

When you look at the problem statement it says that as soon as you find the “elem” value inside the given nested arrays. You need to remove any arrays that contains this “elem”.

When you are stuck, the fastest way to get Hints would be to use the “Get Help” button → “Get a Hint” button (This buttons are located below the “Run Tests” button), which will lead you here for this particular challenge:

freeCodeCamp Challenge Guide: Iterate Through All an Array's Items Using For Loops.

And I assume you have already gone through this hints and solution and you are still facing doubts?

I was thinking of this solution:

function filteredArray(arr, elem) {
let newArr = ;

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

}

}

// Only change code above this line

return newArr;

}

Use the slice() method instead of pop(). Pop removes the last element in the array while slice removes an element at a specific index e.g. arr[i]

You are putting the element in the answer then removing it if it matches, almost like if you were buying apples and you put the apple in cart and then looked at the apple and if it was bad you took out. Why not only put the apple (element) in the cart (array) if it is good (doesn’t have elem).
Also, you update the loop variable ‘i’ in the ‘for’ statement, if you do that again you will skip every other entry in arr.
Note:
One skill that is good to practice is to be able to picture what is happening at each step in your head. When I was first learning I would write out the data and steps on a piece of paper and figure the state of all the variables at each step of the process, if you do that then over time it will come more easily to the point of being able to do it in your head.

so what is the alternative for the for loop

I was replying to the initial post, I see further down where you check before pushing and that is what I meant. As in:

function filteredArray(arr, elem) {
   let newArr = ;

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

return newArr;

}
1 Like

Okay got it now…!!! :grinning: :grinning: