.filter (Javascript) — KneePin

Ok, this is a quick guide in wielding the .filter method in Javascript

below is a simple array, containing objects

song array

now we all tackled the case where we only need certain type of objects from the array (seperate some data from the other, for one purpose or another).

lets says we only need to work on the ‘Rock’ songs in the array.

we used to solve it something around these lines of code

building an array only from the Rock songs, (lines of code match the steps)

we declare a new array to store only rock songs (line 9), than we loop through our original array comparing each objects type in the array to what we looking for (lines 12 -15), and pushing the results into the new array.

pretty simple logic.

Now what if we only had a method that was build to do that, we could save ourselves time and write a more cleaner, elegant code.

The above example uses the .filter method, to solve the same problem. .filter is a built in method of arrays, that does what it says, filters accordingly to our statement (line 19).

.filter will loop through every item in the song[] and will pass over every single item to the inner function as currentSong parameter. The inner function acts as a callback function (callback functions are functions, that are passed to other functions, since functions are objects by themselves they can be passed and stored in other variables or objects), meaning if it returns ‘true’, the filter method will ‘push’ the currentSong into the new array — rockSongs.

Thats it we wrote a more elegant code and took a more professional approach in solving this problem.

hope you found it useful as i did, and share this information with your colleagues :) />

*bonus .reject will give us an array of all the songs that NOT Rock.