It’s the first day of spring! Yay for baby animals, and bumblebees, and flowers, and rain showers and… oh, wait. I’m in Colorado, and it’s been snowing since I woke up this morning.
.filter() methods. Two birds, one stone, baby!
Let’s start off with our shopping cart, which we’ll display as an array of objects. Each object represents a packet of seeds.
.map() is an array method that executes a callback function on each element of a given array. Like
.slice(), this method is nondestructive , meaning the original array will remain unchanged. It returns a new array, populated by the results of the callback function.
One helpful use for
.map() is to retrieve specific information from an array of objects. Let’s start playing with our code. Hit “run” to see the output of our functions.
In the above example, our callback function is written out the long way. ES6 allows us to simplify this using the Arrow Function syntax. Let’s refactor, noticing the results stay the same:
.filter() is also a nondestructive way to manipulate an array. It, again, returns a new array, leaving the original unchanged. It also takes a callback function as an argument, but this callback must return
false. The resulting array from
.filter() is a list of all the elements from the original array for which the callback returns
true. Let’s take a look:
Once again, we can refactor this using ES6 syntax:
My favorite thing about these methods is how clean they look. They also lend themselves well to chaining, and they are generally fun to experiment with.
For a more detailed look at these methods, including optional arguments and more examples, check out MDN’s separate articles on .map() and .filter(). If you really want to understand these methods, try them out yourself! Look for points in your code where you might be able to use
.filter() in lieu of a complicated looping statement, and just give it a try. We’re all learning, after all!