Filter() Method

Hi, im just looking for someone to simply breakdown step by step what is happening in this piece of code using arrow syntax and the filter() method. Like I understand its going through both arrays and seeing what items are the same but I want to be able to understand when each step is happening in the code. For e.g why is there a second arrow etc. Any help would be greatly appreciated.

const justCoolStuff = (firstArray, secondArray) => firstArray.filter(item => secondArray.includes(item));

1 Like

It helps to look towards the docs for this type of thing (they even provide a sandbox to play in): Array.prototype.filter() - JavaScript | MDN

Basically if we break it down, here’s what’s happening:

  • const justCoolStuff = (firstArray, secondArray) => {//function code} declares a function justCoolStuff, that takes arguments (in this case, 2 arrays). The function will do something and maybe even return a value.
  • so what does justCoolStuff do? It runs a filter() method on the first array firstArray.filter().

Now, it’s a bit important to understand what happens under the hood with these types of methods like filter() (they come from functional programming, another example would be reduce() or map() which work very similarly).

  • Filter will iterate through your array (just by being invoked). Here you should really look at the docs to see what is possible (as in, it can iterate but also keep track of indexes and more).
  • In this simple case item => condition, the element being iterated takes the token name of item. It can be any name you want (ideally it should be descriptive of what’s happening). It can be word, or element, or num, etc. depending on circumstance.
  • Then if it meets the condition, it gets added to a new array that eventually gets returned when the iteration is over. The specific condition in this example is secondArray.includes(item) (notice this returns a boolean value).

Thanks very much. This helped a lot.