Iterate Through All an Array's Items Using For Loops - Problem Approach

My question is more philosophical in nature.

When I first started attempting to solve this problem, I kept trying to remove the sub-arrays in question from the array. The solution I landed on (and the solution provided in the Get Hints section) involved just creating a new array that contained all the subarrays except the ones in question.

It seems inefficient, on principle, to create a new array when you could just modify an existing array.

Could anyone shed any light on why FCC doesn’t include a potential solution (in the Get Hints section) for just modifying the existing array? Is it because we hadn’t learned delete yet (that comes a few lessons later)?

Thanks in advance!

It’s generally a bad idea to modify an array that you are iterating over. Adding and removing items changes the length of the array, which is what the loop-termination condition is based on. Modifying an array also changes the index of items in that array, so you may skip certain elements, or repeat operations on the same element multiple times. Modifying an array that you are iterating over can cause errors such as infinite loops and null reference errors and it can cause logical errors because you are trying to hit a moving target.

There are special array methods such as filter and reduce which exist to help you mutate an array. You’ll encounter those later.

2 Likes

Thanks for your swift response, @ArielLeslie!

Last, related question - are there any memory allocation concerns (maybe not in this particular case, or in Javascript necessarily) that should be considered when deciding to mutate arrays vs. generate new arrays?

Only if you are working in specialized fields where memory allocation and/or the time cost of accessing memory are critical. For example, @JeremyLT works on a library for supercomputers and has to worry about that sort of thing.

Even in a situation where you have to pay attention to this sort of thing, often the important part is that memory is being released when you aren’t using it anymore. Different languages handle “garbage collection” differently and when you do a deep-dive on a language you can make sure that you are creating temporary variables in the way that makes the most sense.

1 Like

In general - if your arrays are big, don’t duplicate them because memory movement is expensive. But if you are doing large scale data processing, you probably don’t want to be using JavaScript.

2 Likes