Functional Style TypeScript 2:
Array.filter
Overview
Array.filter provides a declarative API for filtering arrays. That is, it allows you to build a new array that contains all of the elements of an original array that satisfy some condition.
Scenario
Use Array.filter when you need to exclude some elements from an existing array for the purposes of a calculation. It is common to chain map
or reduce
to the result of a filter
.
Example
Suppose we only want to display preferred customers in a certain dashboard, but we have an array with all customers. We could filter the customers as follows.
type Customer{
isPreferred: boolean;
id: string;
name: Name;
}
const customers: Customer[] = buildTestCustomers();
const preferredCustomers = customers.filter(
(customer) => customer.isPreferred;
);
The callback we provide to Array.filter
is called a predicate function. It takes in an element from the array and returns a boolean
that tells filter whether to keep the element in the new array.
Immutability
As for the return value of Array.map
, the filtered array returned from Array.filter
will be a new array and the original array will not be mutated. Care must be taken, however, when the original array's elements are objects if you want to avoid deeply shared references.
Use Cases
Often, you will need to chain a map
or reduce
or forEach
onto the filter
call. For example, you may want to notify every preferred customer of a special sale by email.
customers.filter(
(customer) => customer.isPreferred;
)
.forEach(
(preferredCustomer) => sendNotificationEmail(preferredCustomer, membersOnlySale);
);
Note that here we do not need to save a reference to the result as we are executing a side effect within the forEach
.
Point Free
We can rewrite the code to be point free as follows.
interface Preferable{
isPreferred: boolean;
}
const isPreferred = ({isPreferred}: Preferable) => isPreferred;
const preferredCustomers = customers.filter(
isPreferred
);
Exercises
- Given a
string[]
of input `comments`, filter out all comments longer than 20 characters. - Given a
number[]
callednumbers
, filter out the odd numbers. You may want to use the%
operator. - Given a
number[]
callednumbers
, build a new array calledsquaredEvens
that contains the square of the even elements fromnumbers
.