Basic Data Structures: Iterate Through All an Array's Items Using For Loops - Guide Answer

Tell us what’s happening:

The answer to this challenge that is given in the guide didn’t produce the desired output(Chrome’s console) but it surprisingly passes the tests!

Why is that?

And the comments that show where to begin writing the code are not the same{Spread was used}

Link to the solution page
https://guide.freecodecamp.org/certifications/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops

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

What do you mean it didn’t produce the desired output?

I meant that it didn’t return the filtered array

Yes it does return the filtered array for each test case. Add console.log(newArr) before the return statement and check your browser’s console (Ctrl+Shft+J in Chrome) if you want to validate for yourself.

I tried that but it still returns an empty array

For which test case?

The one in the example
filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)

Using the code provided in the guide, the above test case does return an empty array. I don’t what you are looking at to determine what the returned value is, but if you write the following line before the return statement, you will see an empty array displayed in the browser’s console when the above test case executes.

console.log(newArr);

What do you see in the browser’s console for this test case? Please provide a screenshot.

1

I’m not sure that I understand what you’re talking about, but the challenge wanted to remove ‘3’ from all subsequent arrays so it should return all other arrays not an empty array… is that correct?

You are misunderstanding the challenge instructions (see below).

Modify the function, using a for loop, to return a filtered version of the passed array such that any array nested within arr containing elem has been removed.

The function is called with an array of arrays. You are supposed to return an array containing only arrays which do not have a 3 in them (for this particular test case). Every sub array has the number 3 in it, so you must remove all of the sub arrays, so you are only left with an empty array.

1 Like

Thanks a lot, now I get it
honestly I was trying to remove all 3’s from every inner array to form a new array with these new ones

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution.

Thank you.

Hi, can you please elaborate i–? On first inner loop iteration, i is equal to 0 so i-- results in negative value; -1? What does this achieve?