Array of Objects to Matrix - Problem

Write a function that converts an array of objects arr into a matrix m.

arr is an array of objects or arrays. Each item in the array can be deeply nested with child arrays and child objects. It can also contain numbers, strings, booleans, and null values.

The first row m[0] should be the column names. If there is no nesting, the column names are the unique keys within the objects. If there is nesting, the column names are the respective paths in the object separated by ".".

Each of the remaining rows corresponds to an object in arr. Each value in the matrix corresponds to a value in an object. If a given object doesn't contain a value for a given column, the cell should contain an empty string "".

The columns in the matrix should be in lexicographically ascending order.

Input & Output

Example 1 — Basic Nested Objects
$ Input: arr = [{"b": 1, "a": 2}, {"b": 3, "c": 4}]
Output: [["a","b","c"],["2","1",""],["""3","4"]]
💡 Note: Keys are "a", "b", "c" in lexicographical order. First object has values for "a" and "b", second object has values for "b" and "c".
Example 2 — Deeply Nested Structure
$ Input: arr = [{"a": {"b": 1, "c": 2}}, {"a": {"b": 3}, "d": 4}]
Output: [["a.b","a.c","d"],["1","2",""],["3","","4"]]
💡 Note: Nested objects create dot-notation paths: "a.b", "a.c", "d". Missing values become empty strings.
Example 3 — Mixed Data Types
$ Input: arr = [{"a": null, "b": true}, {"a": "hello", "b": false}]
Output: [["a","b"],["null","true"],["hello","false"]]
💡 Note: Different data types are converted to strings: null → "null", boolean → "true"/"false".

Constraints

  • 1 ≤ arr.length ≤ 1000
  • Each object can be nested up to 1000 levels deep
  • Column names will be valid strings
  • Values can be null, boolean, number, or string

Visualization

Tap to expand
INPUTALGORITHMRESULTArray of Objects[{"b":1,"a":2}, {"b":3,"c":4}]Mixed keys, nested values1Flatten ObjectsConvert nested to dot paths2Collect All KeysFind unique column names3Sort Lexicographically["a", "b", "c"]4Build MatrixHeaders + data rows2D Matrix"a""b""c""2""1""""""3""4"Key Insight:Transform nested object structures into tabular format by flatteningpaths with dot notation and organizing columns alphabetically.TutorialsPoint - Array of Objects to Matrix | Single Pass Approach
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
32.4K Views
Medium Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen