847. Array of Objects to Matrix
You are given an array of elements where each element can be an object, an array, or a primitive value (number, string, boolean, or null). Your task is to convert this array into a matrix where each row represents an element from the input array and each column represents a unique path to a primitive value within that element's nested structure. Paths are constructed by concatenating keys for objects or indices for arrays (treated as keys) using a dot (".") as the separator.
To construct the matrix, first determine the column names, which form the first row. This is done by collecting all unique paths that lead to primitive values across all elements in the array, and then sorting these paths lexicographically in a case-sensitive manner. These sorted paths become the headers of the matrix.
The data rows that follow correspond to each element in the input array. For each column path, if the element contains a value at that path, include that value in the corresponding cell; otherwise, use an empty string ("") to indicate the absence of a value. In the case of arrays, they are treated as objects with keys being the numeric indices represented as strings (for example, the first element of an array has the key "0").
This approach ensures that the resulting matrix comprehensively and consistently represents every primitive value extracted from the nested structure of the input, mapping each value to its corresponding unique path.
Example 1:
Input :
arr = [
  {"user": {"name": "Alice", "age": 30}, "active": true},
  {"user": {"email": "alice@example.com"}, "active": false}
]
Output :
[
  ["active", "user.age", "user.email", "user.name"],
  [true, 30, "", "Alice"],
  [false, "", "alice@example.com", ""]
]
Explanation :
The unique paths are active, user.age, user.email, and user.name. The second object lacks user.age and user.name, while the first lacks user.email. Columns are sorted lexicographically.
Example 2:
Input :
arr = [
  {"data": [{"value": 10}, {"value": 20}]},
  {"data": [15, {"value": 25, "flag": true}]}
]
Output :
[
  ["data.0.value", "data.1.flag", "data.1.value"],
  [10, "", 20],
  ["", true, 25]
]
Explanation :
The first object contributes data.0.value and data.1.value. The second object contributes data.1.flag and data.1.value. Note that data.0 in the second object holds 15 (a primitive), but no nested keys, so no new path is created for it.
Now Your Turn!
Pick the correct output for the given inputInput :
arr =[
  {},
  {},
  {},
]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= arr.length <= 1000.
- The number of unique column paths does not exceed 1000.
- Input arr is a valid JSON array.