Question Bank
JavaScript Object Values to Array: Two Approaches Quiz
Difficulty: Medium
Two seeded approaches to convert an object's values to an array (Object.values spread vs Object.keys.map) plus two companions on Object.entries and ordering pitfalls.
JavaScript Object Values to Array: Two Approaches Quiz
Two seeded approaches to convert an object's values to an array (Object.values spread vs Object.keys.map) plus two companions on Object.entries and ordering pitfalls.
1,026 views
27
Implement toArray(obj) to return an array of the object's own enumerable values, using Object.values and the spread operator. Why is the spread harmless here?
Examples
Example 1:
Input: { a: 1, b: 2, c: 3 }
Output: [1, 2, 3]
Explanation: `Object.values` already returns an array; the spread copies it into a new array literal.Now implement the same function with Object.keys and .map. Why is this version slightly slower, and when would you still pick it?
Examples
Example 1:
Input: { x: 'a', y: 'b' }
Output: ['a', 'b']
Explanation: keys = ['x', 'y']; map(k => obj[k]) projects to the values in the same order.Use Object.entries to turn {a:1,b:2,c:3} into [['a',1],['b',2],['c',3]], and then map it into [{key:'a',value:1}, ...]. When is entries strictly better than keys + indexed lookup?
Examples
Example 1:
Input: { a: 1, b: 2 }
Output: [{ key: 'a', value: 1 }, { key: 'b', value: 2 }]
Explanation: entries yields key/value pairs; destructuring the tuple in the map gives readable names.Ordering pitfall: predict the output of Object.values({ 2: 'a', 1: 'b', 'name': 'c' }). Explain the rule.
Examples
Example 1:
Input: { 2: 'a', 1: 'b', name: 'c' }
Output: ['b', 'a', 'c']
Explanation: Integer-like keys (1 then 2) come first in ascending numeric order; string keys follow in insertion order.Example 2:
Input: { '01': 'x', '1': 'y' }
Output: ['y', 'x']
Explanation: '01' is NOT an integer-like key (leading zero), so '1' is sorted as the integer 1 first and '01' is appended in insertion order.