Array Flatten in JavaScript
What is a Nested Array? A nested array is simply an array that contains other arrays inside it. This nesting can go to any depth (even infinitely). [5, 6, [7, 8]] [5, 6, [7, 8, [8, 9]]] Why Do We N...

Source: DEV Community
What is a Nested Array? A nested array is simply an array that contains other arrays inside it. This nesting can go to any depth (even infinitely). [5, 6, [7, 8]] [5, 6, [7, 8, [8, 9]]] Why Do We Need to Flatten Arrays? Working with deeply nested arrays in real-world applications can be difficult. To make data easier to process, we flatten the array—i.e., convert it into a single-level array. [5, 6, [7, 8]] → [5, 6, 7, 8] [5, 6, [7, 8, [8, 9]]] → [5, 6, 7, 8, 8, 9] Methods to Flatten an Array Using Built-in flat() Method JavaScript provides a built-in method called flat(). let arr = [1, 2, [3, 4], [7, 8, [9, 10]]]; console.log(arr.flat(Infinity)); // Output: [1, 2, 3, 4, 7, 8, 9, 10] flat() takes a depth level as an argument. Infinity ensures the array is flattened completely. Example with limited depth: let arr1 = [1, 2, [3, 4], [7, 8, [9, 10, [5, 6]]]]; console.log(arr1.flat(2)); // Output: [1, 2, 3, 4, 7, 8, 9, 10, [5, 6]] Using Recursion This method manually traverses each element