Just would like some clarification on .map vs .filter

Hi all. As I continue to learn more about basic algorithms in Javascript, it has occurred to me that .map and .filter are very similar. As others have pointed out multiple times in the past, the .map method changes the original array passed through it, while the .filter method does NOT change the original array that is passed through it.

This said, when performing the .map method, if the result is assigned to a new variable, does that not essentially perform the same feat as the .filter method? In other words, when assigning the result of the map method to a new variable, doesn’t the original array on which the map method was passed remain in tact (i.e. there is no change to the original array)? Thanks in advance. This community is awesome.

Map does not modify the original array.

Map returns a new array that is as long as the original array, but with modified contents
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Filter returns a new array that is possibly smaller, where only elements that pass a test remain
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

4 Likes

Ah, thank you. This is why I asked, despite all the documentation I do get confused as I’m trying to intake a lot of new information. Again, I thank you.

That’s what we’re here for. The high order functions take a while to get comfortable with.

1 Like

Just to add to what @JeremyLT pointed out, it made more sense for me to take map and filter quite literally. map takes each element of the array, transforms(maps) them to new values and returns them in a new array leaving the original array unchanged. filter gets elements of the array that meet a certain criterion (filter) and returns them leaving the original array untouched as well.

3 Likes

Thank you! It might take me a while for this to sink in, but as I come across and utilize these methods more and more, hopefully I will begin to understand more intuitively when to use these as well as other array methods. I appreciate all the support I’m finding here!

1 Like