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 info
1const 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 department
8const 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 array
9 (acc[person.dept] ||= []).push(person.name);
// Return accumulator for next iteration
10 return acc;
// Start with empty object
11}, {});
12
// Output: { HR: ["Alice", "Carol"], IT: ["Bob", "Dave"] }
13console.log(byDept);

Output

{ HR: [ 'Alice', 'Carol' ], IT: [ 'Bob', 'Dave' ] }
Practice typing this code

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

More JavaScript examples at level 4

← JavaScript typing practice