请实现一个flattenDeep函数,把多维数组扁平化

function flattenDeep(arr) {
  const flattened = [];

  function recurse(subArr) {
    for (const element of subArr) {
      if (Array.isArray(element)) {
        recurse(element);
      } else {
        flattened.push(element);
      }
    }
  }

  recurse(arr);
  return flattened;
}


// Test cases
console.log(flattenDeep([1, [2, [3, [4]], 5]])); // Output: [1, 2, 3, 4, 5]
console.log(flattenDeep([1, 2, [3, 4], 5])); // Output: [1, 2, 3, 4, 5]
console.log(flattenDeep([1, [2], [3, [4]]])); // Output: [1, 2, 3, 4]
console.log(flattenDeep([])); // Output: []
console.log(flattenDeep([[[[]]]])); // Output: []
console.log(flattenDeep([[1], [2], [3]])); // Output: [1, 2, 3]

// Example with different data types
console.log(flattenDeep([1, "hello", [2, true, [3, null, [4, undefined]]], 5])); // Output: [1, "hello", 2, true, 3, null, 4, undefined, 5]

This implementation uses a recursive helper function recurse to iterate through the nested arrays. It checks if each element is an array itself. If so, it calls recurse again on that sub-array. Otherwise, it pushes the element onto the flattened array. This continues until all nested arrays have been traversed and all elements have been added to the flattened array. This approach handles deeply nested arrays and various data types effectively.

Here's a slightly more concise version using reduce and the spread syntax, though recursion is generally more readable for deep flattening:

function flattenDeep(arr) {
  return arr.reduce(
    (acc, val) =>
      Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val),
    []
  );
}

// Test cases (same output as above)
console.log(flattenDeep([1, [2, [3, [4]], 5]])); // Output: [1, 2, 3, 4, 5]
console.log(flattenDeep([1, 2, [3, 4], 5])); // Output: [1, 2, 3, 4, 5]
console.log(flattenDeep([1, [2], [3, [4]]])); // Output: [1, 2, 3, 4]
console.log(flattenDeep([])); // Output: []
console.log(flattenDeep([[[[]]]])); // Output: []
console.log(flattenDeep([[1], [2], [3]])); // Output: [1, 2, 3]
console.log(flattenDeep([1, "hello", [2, true, [3, null, [4, undefined]]], 5])); // Output: [1, "hello", 2, true, 3, null, 4, undefined, 5]

Both versions achieve the same result, providing a robust flattenDeep function. Choose the one that best suits your coding style and project requirements. The recursive version is generally preferred for clarity when dealing with deeply nested structures.

posted @ 2024-11-23 08:23  王铁柱6  阅读(7)  评论(0)    收藏  举报