javascript / intermediate
Snippet
Array Filtering and Projection via Pure Transformation Pipes
Custom Angular pipes can perform efficient data transformations on arrays by combining JavaScript array methods like filter and map. Marking the pipe as pure ensures the transform function only re-executes when the array reference or primitive arguments change, avoiding unnecessary recalculations on each change detection cycle.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { Pipe, PipeTransform } from '@angular/core';interface UserRecord {id: number;name: string;isActive: boolean;department: string;}@Pipe({ name: 'activeDepartmentFilter', pure: true, standalone: true })export class ActiveDepartmentFilterPipe implements PipeTransform {transform(users: readonly UserRecord[] | null, targetDept: string): string[] {if (!users || !Array.isArray(users)) {return [];}return users.filter((user): user is UserRecord => user.isActive && user.department === targetDept).map(user => user.name);}}
angular
Breakdown
1
@Pipe({ name: 'activeDepartmentFilter', pure: true, standalone: true })
Registers a pure standalone pipe, caching results until input references mutate.
2
transform(users: readonly UserRecord[] | null, targetDept: string): string[] {
Accepts an immutable array of user records and returns a projected array of strings.
3
if (!users || !Array.isArray(users)) { return []; }
Performs defensive input checking against null, undefined, or malformed data types.
4
.filter((user): user is UserRecord => user.isActive && user.department === targetDept)
Uses a TypeScript custom type guard within the array filter method to filter records meeting criteria.