Question Bank
JavaScript Group Students by ID: Two Approaches Quiz
Difficulty: Medium
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.
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.
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.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'.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.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.