To flatten a multi-dimensional zig-zag array in JavaScript, you can use a combination of loops and array manipulation techniques.
Here is an example of how you might flatten a multi-dimensional zig-zag array:
const array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
// Flatten the array using a loop
const flatArray = [];
for (const subArray of array) {
flatArray.push(...subArray);
}
console.log(flatArray); // Outputs: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In this example, the flatArray
array is initialized as an empty array. A loop is used to iterate over the elements of the array variable, which represents the multi-dimensional zig-zag array. For each element, the spread operator (...)
is used to add the elements of the subarray to the flatArray
array.
This will result in a flattened array that contains all of the elements of the original array in the order they appear.
Alternatively, you can use the Array.prototype.flat
method to flatten the array, as follows:
const array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const flatArray = array.flat();
console.log(flatArray); // Outputs: [1, 2, 3, 4, 5, 6, 7, 8, 9]
The flat method will return a new array that is one level deeper than the input array. To flatten a multi-dimensional array with more than one level of nesting, you can call the flat method multiple times or pass it a depth parameter. For example:
const array = [[1, 2, 3], [4, [5, 6], 7], [8, 9]];
const flatArray = array.flat(2);
console.log(flatArray); // Outputs: [1, 2, 3, 4, 5, 6, 7, 8, 9]
This will result in a flattened array that contains all of the elements of the original array in the order they appear.
Top comments (0)