写一个方法把多维数组降维
/**
* Flattens a multi-dimensional array into a single-dimensional array.
*
* @param {Array} arr The multi-dimensional array to flatten.
* @param {boolean} [deep=false] If true, recursively flattens nested arrays. Otherwise, only flattens one level.
* @returns {Array} The flattened array.
*/
function flattenArray(arr, deep = false) {
const flattened = [];
for (const element of arr) {
if (Array.isArray(element)) {
if (deep) {
flattened.push(...flattenArray(element, true)); // Recursive call for deep flattening
} else {
flattened.push(...element); // Shallow flattening
}
} else {
flattened.push(element);
}
}
return flattened;
}
// Examples
const arr1 = [1, 2, [3, 4]];
const flat1 = flattenArray(arr1); // Shallow flatten
console.log(flat1); // Output: [1, 2, 3, 4]
const arr2 = [1, 2, [3, [4, 5]]];
const flat2 = flattenArray(arr2); // Shallow flatten
console.log(flat2); // Output: [1, 2, 3, [4, 5]]
const deepFlat2 = flattenArray(arr2, true); // Deep flatten
console.log(deepFlat2); // Output: [1, 2, 3, 4, 5]
const arr3 = [1, [2, [3, [4]]], 5];
const deepFlat3 = flattenArray(arr3, true); // Deep flatten
console.log(deepFlat3); // Output: [1, 2, 3, 4, 5]
const arr4 = []; // Empty array
const flat4 = flattenArray(arr4);
console.log(flat4); // Output: []
const arr5 = [1, 2, 3]; // Already flat array
const flat5 = flattenArray(arr5);
console.log(flat5); // Output: [1, 2, 3]
Explanation and Key Improvements:
deepParameter: Allows for both shallow and deep flattening controlled by a boolean flag. This makes the function more versatile.- Recursion for Deep Flattening: The
deep = trueoption uses recursion to handle nested arrays of any depth. - Spread Syntax (
...): Uses the spread syntax (...) for more concise and efficient array concatenation. - Clearer Comments and Example Usage: Provides better documentation and more comprehensive examples to demonstrate the function's behavior with different inputs, including edge cases like empty and already-flat arrays.
- Handles various edge cases properly: Empty arrays, already flat arrays, and deeply nested arrays are all handled correctly.
This improved version is more robust, efficient, and easier to understand and use in various scenarios. It represents a best-practice approach to array flattening in JavaScript.
浙公网安备 33010602011771号