Filter

Here's another function I use all the time. Let me give you a simple example:

[1, 2, 3, 4, 5, 6, 7, 8, 9].filter((x) => x % 2 === 0)

This code returns

[ 2, 4, 6, 8 ]

filter is another array method. It takes a function as a parameter and calls that parameter on every one of its elements. filter returns an array including every element for which the function returned a truthy value. Truthy values are anything that's not 0, undefined, or null.

Ok, let's do a more complicated example. Let's say you run a space dock and need to find all docked ships with a warp drive.

Here's a list of your ships:

var ships = [  
    {
        name: 'Enterprise',
        captain: 'Picard',
        propulsion: ['impulse', 'warp']
    },
    {
        name: 'Millenium Falcon',
        captain: 'Han Solo',
        propulsion: ['boosters', 'hyperspace']
    },
    {
        name: 'Voyager',
        captain: 'Janeway',
        propulsion: ['impulse', 'warp', 'slipstream']
    },
    {
        name: 'TARDIS',
        captain: 'The Doctor',
        propulsion: ['Atron Engine']
    }
]

And here's how I'd grab only the ships with warp drive:

ships.filter((ship) => ship.propulsion.indexOf('warp') >= 0)  

You know, that doesn't read too well to my way of thinking. Some might disagree, but I think it might be worth while to add a has method to arrays:

Array.prototype.has = function (element) { return this.indexOf(element) >= 0 }  

After that, we can do this:

console.log(ships.filter((ship) => ship.propulsion.has('warp')))  

Which I think is pretty sweet.

It's probably not a good idea to add tons of methods to array. Some people would say you shouldn't do it at all. But I think this adds a certain elegance.

Looking for a software developer?