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 ages1const people = [2 { name: "Alice", age: 25 },3 { name: "Bob", age: 30 },4 { name: "Charlie", age: 25 }5];// Group people by age using reduce6const grouped = people.reduce((acc, p) => { // ||= creates array if it doesn't exist // Then push the name to that age group7 (acc[p.age] ||= []).push(p.name); // Return the accumulator8 return acc;9}, {});// Print { '25': ['Alice', 'Charlie'], '30': ['Bob'] }10console.log(grouped);Output
{ '25': [ 'Alice', 'Charlie' ], '30': [ 'Bob' ] }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