Group Array Objects by Key
Group Array Objects by Key is a reusable JavaScript snippet. Groups an array of objects by a specified key value, returning an object with keys as group names and values as arrays. The full implementation: // Method 1: Object.groupBy() (ES2024) const grouped = Object.groupBy(items, item => item.category) // Method 2: Manual (for older environments) function groupBy(arr, key) { return arr.reduce((acc, item) => { const group = item[key] ;(acc[group] = acc[group] || []).push(item) return acc }, {}) } // Usage const users = [ { name: 'Alice', role: 'admin' }, { name: 'Bob', role: 'user' }, { name: 'Charlie', role: 'admin' }, ] groupBy(users, 'role') // { admin: [Alice, Charlie], user: [Bob] } This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.