FreeCodeCamp and JavaScript: The filter() Method

Today, we’re going to look at the filter() method, which will create a new array from the arguments sent to it that contain only the elements that pass the test the filter() method is written to perform.  That’s a mouthful, so I think looking at MDN’s examples will make it clearer than reading that sentence.

First, the syntax of the filter() method according to MDN:

arr.filter(callback[, thisArg])

Okay, that’s perfectly clear.

Or not.

Anyway, looking at the above, we can see that there are two parameters for the filter() method.  First is the callback, and this is basically the test you’ll perform to “filter” the items you want out of the arguments.  It will be written as a function, with the arguments element – the element it is currently working on, index – the index of the element it is currently working on, and array, which is the array it’s processing.  Finally, if the element passes the test, true is returned, and if not, false is returned.  If the element doesn’t have a value assigned to it or doesn’t exist, then it’s skipped.

Second is an optional parameter, thisArg, which MDN defines as “Optional. Value to use as this when executing callback.”  The this parameter is a whole other blog post or three unto itself, so I’m not going to do much with this one for this post!

As with the slice method we talked about, the original array isn’t modified.  Also, if any changes are made to the original array AFTER filter() is called like changing, adding, or deleting an element, the output of filter() doesn’t change with it.  You’d have to run filter() again.

Now, let’s take a look at MDN’s example.  We want to “filter” out all the elements in an array that are less than 10 and only keep the ones that are greater than or equal to 10.  Here’s their code:

function isBigEnough(value) {
  return value >= 10;
}

The first line calls the filter() method, passing the arguments under the variable value.  The second line returns the elements only if they are greater than or equal to 10.  To call this function, we use the following line of code:

var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);

So what we’re doing is calling a filter method isBigEnough, passing it the array [12, 5, 8, 130, 44], and assigning the result of the filtering to the variable filtered.  Our output is:

[12, 130, 44]

which is all the elements meeting the condition.  The ones that do not – 5 and 8, are “filtered” out.

Let’s look at a slightly more complicated example next.  This one takes data in JSON format – a way of representing data in JavaScript, something else we can cover another time! – and goes through it looking for items whose ID are numeric and/or not zero.  Here’s our JSON information stored in a variable called arr.  Note that this is an object, not an array!  They could perhaps have chosen something less confusing for a variable name!

var arr = [
  { id: 15 },
  { id: -1 },
  { id: 0 },
  { id: 3 },
  { id: 12.2 },
  { },
  { id: null },
  { id: NaN },
  { id: ‘undefined’ }];

Note that the last four elements don’t meet the criteria.  Now, here’s the filter code:

var invalidEntries = 0;
function filterByID(obj) {
  if (‘id’ in obj && typeof(obj.id) === ‘number’ && !isNaN(obj.id)) {
  return true;
  } else {
  invalidEntries++;
  return false;
  }}

First, we create a variable called invalidEntries that acts as a counter.  We do this outside the function so it’s a global variable (review the concept of scope if you don’t know what this means).  Next we declare the function filterByID and pass it the argument obj.  Inside the function we have an if-then statement.  If we have an ID in the Object, and that id is a number, and if that id is not -not-a-number (yes, that’s torturous) then return true, otherwise increment invalidEntries because the element doesn’t meet any of the criteria and return false.

That’s still a mouthful so let’s continue on, then look at how it executes.  We call the function like so:

var arrByID = arr.filter(filterByID);

We’re calling the filter() function filterByID, passing it the JSON object arr, and storing the result in the variable arrByID. We get the following results:

console.log(‘Filtered Array\n’, arrByID);
// Filtered Array// [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }]
console.log(‘Number of Invalid Entries = ‘, invalidEntries);
// 4

The first result is the filtered array with the elements that met all the criteria.  I’m a little confused by MDN’s answer since they said they want items that are numeric AND non-zero, and there’s zero as the third element, but I’m just going to assume that one was missed in the proofreading process.  Anyway, you’ll note that there are four invalid entries (the last four entries as we noted above).

So the first value passed to the function is {id: 15}.  The test looks at this and sees that it is indeed an id in obj, then notes that its type is indeed a number and it is not NaN.  Therefore it passes and we go on to the second element, {id: 1}, which passes all three tests, and so on until we get to the sixth element, which is {}.  This is not an id in obj; in fact it’s empty, so it fails the test.  Element seven is {id: null}, which is an id in obj, passing the first test, but it’s non-numeric, so it fails. Element 8 is NaN and fails the third test.  Finally, the last element is undefined, so it fails as well.

And there you go.  That’s the filter() method in action!

Advertisements

One thought on “FreeCodeCamp and JavaScript: The filter() Method

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s