如何将扁平化数组还原为原始嵌套数组结构?
Great question—hardcoding positions is definitely not scalable, so let's fix that with a dynamic approach that adapts to any nested structure.
The key realization here is that when you flattened your original nested array, you were essentially traversing it in a depth-first order (the standard way most flatten functions work), which preserves the exact sequence of primitive values. To restore the structure, we just need to replicate that same traversal, replacing each original value with the next element from your modified flat array.
Recursive Solution (Simple & Readable)
This is the easiest way to implement it, especially if your nested structure isn't extremely deep (to avoid stack overflow). We'll use a pointer to track our position in the modified flat array, then recursively walk through the original structure, replacing values as we go:
function restoreNestedStructure(originalStructure, modifiedFlatArray) { let currentIndex = 0; // Helper function to traverse and replace values const traverse = (element) => { if (Array.isArray(element)) { // Recursively process each item in the array return element.map(item => traverse(item)); } else { // Grab the next value from the modified array and move the pointer return modifiedFlatArray[currentIndex++]; } }; return traverse(originalStructure); } // Test it with your example: const original = [[[1, 2], [3, 4], [5, 6]], [7, 8, 9, 10]]; const modifiedFlat = [1, 2, 3, 4, 12515, 25125, 12512, 8, 9, 10]; const restored = restoreNestedStructure(original, modifiedFlat); console.log(restored); // Output: [[[1,2],[3,4],[12515,25125]],[12512,8,9,10]]
Iterative Solution (For Deep Structures)
If your nested array is extremely deep (like thousands of levels), recursion might hit a stack limit. In that case, use an iterative approach with a stack to simulate the traversal:
function restoreNestedStructureIterative(originalStructure, modifiedFlatArray) { let currentIndex = 0; // Make a deep copy of the original structure to avoid modifying it directly const result = JSON.parse(JSON.stringify(originalStructure)); const stack = [result]; while (stack.length > 0) { const currentElement = stack.pop(); if (Array.isArray(currentElement)) { // Push elements in reverse order so we process left-to-right for (let i = currentElement.length - 1; i >= 0; i--) { if (Array.isArray(currentElement[i])) { stack.push(currentElement[i]); } else { // Replace the primitive value with the next modified one currentElement[i] = modifiedFlatArray[currentIndex++]; } } } } return result; }
Key Notes
- Traversal Order: This works assuming your flattening used depth-first order (which is standard). If you used a different order (like breadth-first), just adjust the traversal logic in the restore function to match.
- Element Count: Ensure your modified flat array has exactly the same number of elements as the original nested structure (counting all primitive values)—otherwise, you'll get index errors or incomplete replacements.
- Language Agnostic: The logic translates to other languages too. For example, in Python, you'd use a generator or a mutable index variable with recursive/iterative traversal.
内容的提问来源于stack exchange,提问作者SirPeople

