Array GroupBy Simulation in JavaScript

Level 4222 keystrokes

Grouping array elements by a property can be achieved using reduce with logical assignment.

JavaScript code

// Create an array of people with ages
1const people = [
2 { name: "Alice", age: 25 },
3 { name: "Bob", age: 30 },
4 { name: "Charlie", age: 25 }
5];
// Group people by age using reduce
6const grouped = people.reduce((acc, p) => {
// ||= creates array if it doesn't exist
// Then push the name to that age group
7 (acc[p.age] ||= []).push(p.name);
// Return the accumulator
8 return acc;
9}, {});
// Print { '25': ['Alice', 'Charlie'], '30': ['Bob'] }
10console.log(grouped);

Output

{ '25': [ 'Alice', 'Charlie' ], '30': [ 'Bob' ] }
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.

  • ,× 7
  • :× 6
  • "× 6
  • ;× 5
  • .× 5
  • (× 5
  • )× 5
  • {× 5
  • }× 5
  • =× 4

More JavaScript examples at level 4

← JavaScript typing practice