javascript / intermediate
Snippet
Reactive Array Filtering and Multi-Criteria Sorting Using Signals
Using computed signals with modern immutable array methods like `toSorted()` and `filter()` creates declarative, auto-updating derived state. Whenever filtering signals or sort criteria change, Angular recalculates the resulting array projection without mutating the underlying dataset.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { Component, signal, computed } from '@angular/core';export interface Product {id: number;name: string;price: number;category: string;}@Component({selector: 'app-product-list',standalone: true,template: `<!-- Template renders sortedProducts() -->`})export class ProductListComponent {readonly products = signal<Product[]>([{ id: 1, name: 'Desk', price: 250, category: 'Furniture' },{ id: 2, name: 'Chair', price: 120, category: 'Furniture' },{ id: 3, name: 'Mouse', price: 45, category: 'Electronics' }]);readonly selectedCategory = signal<string>('Furniture');readonly sortDirection = signal<'asc' | 'desc'>('asc');readonly sortedProducts = computed(() => {const category = this.selectedCategory();const direction = this.sortDirection();return this.products().filter(item => item.category === category).toSorted((a, b) => direction === 'asc' ? a.price - b.price : b.price - a.price);});}
angular
Breakdown
1
readonly sortedProducts = computed(() => {
Declares a derived signal that memoizes computations and updates automatically when dependencies change.
2
.filter(item => item.category === category)
Filters the source product collection to match the active category filter state.
3
.toSorted((a, b) => direction === 'asc' ? a.price - b.price : b.price - a.price);
Creates a sorted shallow copy of the filtered array based on price without mutating original state.