javascript / intermediate
Snippet
Sorting Reactive Arrays with Locale-Aware Collators
Standard array sorting can fail on accented or localized characters (like umlauts in German). Using ECMAScript's immutable `Array.prototype.toSorted()` inside a computed property alongside `Intl.Collator` preserves original array state while ensuring deterministic, culture-aware alphabetization without mutating reactive dependencies.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { ref, computed } from 'vue';const products = ref([{ id: 1, name: 'Äpfel', price: 2.5 },{ id: 2, name: 'Zitronen', price: 3.0 },{ id: 3, name: 'Bananen', price: 1.8 }]);const collator = new Intl.Collator('de', { sensitivity: 'base' });const sortedProducts = computed(() => {return products.value.toSorted((a, b) => {return collator.compare(a.name, b.name);});});
vue
Breakdown
1
const collator = new Intl.Collator('de', { sensitivity: 'base' });
Configures a reusable, high-performance internationalization collator object for German linguistic rules.
2
return products.value.toSorted((a, b) => {
Produces a new shallow copy of the sorted array without directly mutating the source reactive reference.
3
return collator.compare(a.name, b.name);
Applies localized string comparison order between two product names.