The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

Filter an Array with Truthy Values

Filter an Array with Truthy Values

6:44
Array filter creates a new array with all elements that pass the test implemented by the provided function. In this lesson we discuss how only a truthy or falsey value is required as the return value to the function, which in turns allows us to be creative in how we perform the filter. We end the lesson by looking at an example showing how chaining multiple array methods together can lead to very nice, declarative code.
Watch this lesson now
Avatar
egghead.io

Array filter creates a new array with all elements that pass the test implemented by the provided function. In this lesson we discuss how only a truthy or falsey value is required as the return value to the function, which in turns allows us to be creative in how we perform the filter. We end the lesson by looking at an example showing how chaining multiple array methods together can lead to very nice, declarative code.

Avatar
Ihor

On 2m:50s there is an unsecure pattern to use with arrays or objects.

var people = [
  {
    name: 'Ben'
  },
  {
    name: 'Bob',
    pets: []
  }
]

var filtered = people.filter(x => x.pets)

You might expect empty array but result is:

filtered = {
      name: 'Bob',
      pets: []
    }

because in JS each of these lines will produce 'YES'

if({}) console.log('YES')
if([]) console.log('YES')
In reply to egghead.io
Avatar
Stephen

You're right, and it's a very easy fix.

var people = [
  {
    name: 'Ben'
  },
  {
    name: 'Bob',
    pets: []
  },
  {
    name: 'Stephen',
    pets: ['Charlie']
  }
];

var filtered = people.filter(x => x.pets && x.pets.length > 0);
In reply to Ihor
Avatar
Robert Smith

This might come under the realm of premature optimisation, but wouldn't it be better, instead of chaining together two filter methods to instead do both checks simultaneously inside of a single filter method?

I get the immense power that chaining provides and this demo illustrates that well, but we should be careful when doing this over very large data sets; of course in the provided example the difference would be negligible.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?