javascript / intermediate
Snippet
Filtering Object Collections with a Pure Array Pipe
Custom pure pipes optimize array transformations in templates by caching results and executing transform only when input reference identity or primitive arguments change. This ensures predictable, immutable collection filtering without unnecessary recalculations during change detection cycles.
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';export interface Item {id: number;name: string;category: string;}@Pipe({name: 'filterByCategory',standalone: true,pure: true})export class FilterByCategoryPipe implements PipeTransform {transform(items: Item[] | null | undefined, category: string): Item[] {if (!items || !category) {return items ?? [];}return items.filter(item => item.category.toLowerCase() === category.toLowerCase());}}
angular
Breakdown
1
pure: true
Declares the pipe as pure, meaning transform is only invoked when the input array reference or category string changes.
2
transform(items: Item[] | null | undefined, category: string): Item[] {
Defines the transformation signature accepting typed array inputs and nullish safety fallbacks.
3
return items.filter(item => item.category.toLowerCase() === category.toLowerCase());
Performs an immutable array filter operation matching items case-insensitively by category.