Skip to content

Instantly share code, notes, and snippets.

@peetklecha
peetklecha / mapVsFilter.md
Created March 5, 2020 20:39
Sorting out map and filter.

We have now been using array methods for a while, and two in particular have seen a lot of use: .map and .filter. Y'all have mostly been using these successfully, but we've noticed some issues especially with how you're using .filter so I wanted to take some time to clarify. Even if you feel like you understand these methods, read closely -- part of the issue is that you can get away with misusing these methods to some degree without realizing it, only to have it bite you later.

Map

If I call .map on array A, it will return a new array, B, which has the same length as A. The elements of B will be based on the elements of A, according the callback I gave it. In essence I am transforming each element in A into a new element in B, which is why B must have the same length as A. Whatever is returned by the callback you pass into .map is what goes into B, which is why it's important not to forget to return from your .map-callback.

A = [1,2,3]
A.map(x => x+2) => [3,4,5]