Array GroupBy Pattern in JavaScript
Level 4275 keystrokes
Uses reduce with logical assignment to group array elements by a property.
JavaScript code
// Create an array of people with department info1const people = [2 { name: "Alice", dept: "HR" },3 { name: "Bob", dept: "IT" },4 { name: "Carol", dept: "HR" },5 { name: "Dave", dept: "IT" }6];7 // Use reduce to group people by department8const byDept = people.reduce((acc, person) => { // ||= is logical OR assignment: assigns [] if acc[dept] is falsy // Then push the person's name to the department's array9 (acc[person.dept] ||= []).push(person.name); // Return accumulator for next iteration10 return acc;// Start with empty object11}, {});12 // Output: { HR: ["Alice", "Carol"], IT: ["Bob", "Dave"] }13console.log(byDept);Output
{ HR: [ 'Alice', 'Carol' ], IT: [ 'Bob', 'Dave' ] }Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
"× 16,× 9:× 8{× 6}× 6;× 5.× 5(× 5)× 5=× 4