JavaScript Group Students by ID: Two Approaches Quiz
Two seeded approaches to group an array of student records by id (reduce + dict and the `in` operator), plus two companions on Map and Object.groupBy.
Question Bank
Medium
JavaScript
4 questions
quiz
arrays
hash-map
array-manipulation-patterns
419 views
8
Group an array of { id, score } records by id using reduce and an in-operator branch on the accumulator.
Examples
Example 1:
Input: [{id:1, score:11},{id:2, score:64},{id:1, score:87}]
Output: { 1: [11, 87], 2: [64] }
Explanation: Keys are student ids; values are the scores collected in iteration order.function groupArray(arr) {
// your solution comes here, using reduce + `in`
}Refresher on the in operator: what does each of the following expressions return, and why?
Examples
Example 1:
Input: 'make' in { make: 'Honda', model: 'Accord' }
Output: true
Explanation: `in` checks for an own (or inherited) property key on the right-hand operand.Example 2:
Input: 0 in ['redwood', 'bay']
Output: true
Explanation: Arrays expose indices as own keys, so 0 is a valid key on a non-empty array.Example 3:
Input: 'bay' in ['redwood', 'bay']
Output: false
Explanation: `in` tests KEYS, not values; the value 'bay' is at index 1, but there is no key 'bay'.// Predict each output:
console.log('make' in { make: 'Honda', model: 'Accord', year: 1998 });
console.log(0 in ['redwood', 'bay', 'cedar']);
console.log('bay' in ['redwood', 'bay']);
console.log('length' in ['redwood']);
console.log('PI' in Math);Implement the same grouping with a Map instead of a plain object. Why is Map the safer choice when the grouping keys come from user input?
Examples
Example 1:
Input: [{ id: '__proto__', score: 1 }, { id: 'a', score: 2 }]
Output: Map { '__proto__' => [1], 'a' => [2] }
Explanation: Map treats `__proto__` as an ordinary key; a plain object would either inherit Object.prototype shenanigans or pollute it.function groupByMap(arr) {
// your solution comes here, using a Map
}Use Object.groupBy (ES2024, stage 4, available in Node 21+ and modern browsers) to express the same grouping as a one-liner. What does it return, and how does it differ from the Q1 shape?
Examples
Example 1:
Input: Object.groupBy([{id:1,score:11},{id:2,score:64}], item => item.id)
Output: { 1: [{id:1,score:11}], 2: [{id:2,score:64}] }
Explanation: groupBy returns buckets of the ORIGINAL items, not a projected field like score.// Requires Node 21+ or a modern browser.
const students = [
{ id: 1, score: 11 },
{ id: 2, score: 64 },
{ id: 1, score: 87 },
];
const grouped = Object.groupBy(students, (s) => s.id);
console.log(grouped);