javascript / intermediate
Snippet
Grouping and Partitioning Reactive Array Data in Vue
Transforming reactive array state with Array.prototype.reduce inside a Vue computed property provides structured, categorized dictionary data that updates automatically upon item changes.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { ref, computed } from 'vue';export function useCategorizedProducts(initialList = []) {const products = ref(initialList);const groupedByCategory = computed(() => {return products.value.reduce((acc, product) => {const category = product.category ?? 'Uncategorized';if (!acc[category]) {acc[category] = [];}acc[category].push(product);return acc;}, {});});return { products, groupedByCategory };}
vue
Breakdown
1
const products = ref(initialList);
Initializes a reactive ref containing an array of item objects.
2
return products.value.reduce((acc, product) => {
Iterates through the reactive array to aggregate items into an object dictionary.
3
const category = product.category ?? 'Uncategorized';
Uses nullish coalescing to assign a fallback category key for items without one.
4
acc[category].push(product);
Appends the current item to its matching bucket array.