Changing an Array - Iterator methods - Mini Linter

Hello people,

TLDR;
What is a commonly used way to iterate and change some parts of an array?

During the Mini Linter project I was thinking about Task 8c:
image

I started thinking about the best way and most commonly used way to iterate through an Array with the possibility of changing certain indices and did some experiments:

image

  1. forEach loop (did not work)
    image

  2. for of loop (did not work)
    image

  3. forEach loop with additional parameter index and array (worked)
    image

  1. map method (worked)
    image

Now can someone explain to me why 1 and 2 do not work?
What is the most common approach to this?

Thanks,
Paul

Hi Paul,
the methods 1 and 2 do not work because you don’t do anything with the values like logging them to the console or pushing them to a new array. A for loop does not alter the array passed in.
The forEach method executes a provided function on each item. It doesn’t return a copy like the map method does.
In your thirs approach you’re overwriting each array item by assigning the new value to the array itself, that’s why it works.

The most common method to do this task would be using the .filter() method.

2 Likes

Thanks for your answer…

In example 1, 2 and 3 I am taking the current element of the array I am iterating through, checking if the element is equal 200 and if yes, setting its value to 200.

In my understanding element in this case is the same as array[index].
Obviously since the code is not doing what I want, this is not correct, but I would like to understand why.

In my understanding filter() checks a condition (through a function) and writes all elements that return true in a new array. It doesn’t change certain elements, does it?

In example 1 and 2 you reassign the value of the variable element, but that is only available within the function scope. Some array methods alter the original array when applied by overwriting the values with the returned values. But the forEach method returns undefined. From this article about the difference between .map() and .forEach():

Like map , the forEach() method receives a function as an argument and executes it once for each array element. However, instead of returning a new array like map , it returns undefined.

No, it is not the same. element is a variable the current item value is assigned to while array is a reference to the original array.

That’s right. The filter method does not overwrite the array as well as the map method and forEach. None of them do. You can reassign the variable the original array is assigned to:

let array = ['one', 'two', 'three']
array = array.filter(el => el !== 'one');
console.log(array); // ['two', 'three']
1 Like

That is the piece I was missing.

Thanks Mirja for helping me understand this topic :wink:

1 Like