Tap Forms JavaScript Scripting 102
Forms, Records, Fields, Values
by T. L. Ford

Section 8: Filtering

Suppose we want a report of just cats? We could just do a check for cats before concatenating the name onto the report_string variable.

This certainly works, but suppose we had a lot of cats and a lot of dogs and a lot of other kinds of animals? It would make sense to only sort cats and only loop through cat records, rather than the whole dataset. This is where JavaScript's array filter() becomes useful.

SQL
SELECT * FROM tbl WHERE LOWER(fld)='cat' ORDER BY [Animal Name];

There are several syntax variations for filter() with different degrees of complexity and comprehensibility. I'm only going to cover the simple one that looks a lot like our sort() example.

Unlike sort(), which sorts the original array, filter() returns a new array so we'll need a variable to hold the new array.

This syntax is similar to the array.sort() function because we are passing a condition function to the array.filter() function.

This is the filter method of the array object:

var cat_records = rescue_animals_records.filter(function(a) {
  return a.getFieldValue(animal_kind_id).toLowerCase() == "cat";
});

This is the condition function:

var cat_records = rescue_animals_records.filter(function(a) {
  return a.getFieldValue(animal_kind_id).toLowerCase() == "cat";
}
);

The arbitrarily named parameter to the condition function (a) will represent an element in your array list, whatever that element is - string, number, field object, record object, etc.

var cat_records = rescue_animals_records.filter(function(a) {
  return a.getFieldValue(animal_kind_id).toLowerCase() == "cat";
});

If the condition function returns true, a will appear in the new array.

We implement this .filter() function in our report code and it looks like this:

Which produces the exact same report in a different way that would run much faster for large datasets.

NEXT - Section 9: Shortcuts to Objects