首页 > 解决方案 > 使用递归展平数组内的数组

问题描述

你能告诉我为什么这段代码不能正常工作吗?

flatten 函数假设从输入数组中的任何数组中删除值并将这些值作为数组返回。

function flatten(arr) {
  //create a new array
  let newArr = [];

  //create a helperFunction
  function helperFunction(helperArr) {
    //if its an empty array
    if (helperArr.length === 0) {
      return;
    }

    //get the first value from the array and remove the value
    let firstArrVal = helperArr.shift();
    let isAnArray = Array.isArray(firstArrVal);

    //if value is an array 
    if (isAnArray) {
      //call recursive function on value
      return helperFunction(firstArrVal);
    }
    //if value isnt an array
    else {
      //add value to new array
      newArr.push(firstArrVal);
      //call recursive function on the array
      return helperFunction(helperArr);
    }
  }

  //call helperFunction
  helperFunction(arr);

  //return new array
  return newArr;
}

console.log(flatten([1, [2, [3, 4],
  [
    [5]
  ]
]]));

// Correct output - [1, 2, 3, 4, 5] - Mine - [1, 2, 3, 4]

对于输入[1, [2, [3, 4], [[5]]]],正确的输出是[1, 2, 3, 4, 5](我的 - [1, 2, 3, 4]

标签: javascriptarraysrecursion

解决方案


您需要遍历子数组的所有元素,并push对其进行调用或调用helperFunction。您当前的

    let firstArrVal = helperArr.shift();
    let isAnArray = Array.isArray(firstArrVal);

只会合并第一个嵌套值,但不会合并第 0 个之后的任何嵌套索引。for对数组中的每个值使用循环:

function flatten(arr) {
  //create a new array
  let newArr = [];

  //create a helperFunction
  function helperFunction(helperArr) {
    //if its an empty array
    if (helperArr.length === 0) {
      return;
    }
    for (let i = 0; i < helperArr.length; i++) {
      const val = helperArr[i];
      let isAnArray = Array.isArray(val);

      //if value is an array 
      if (isAnArray) {
        //call recursive function on value
        helperFunction(val);
      }
      //if value isnt an array
      else {
        //add value to new array
        newArr.push(val);
      }
    }
  }

  //call helperFunction
  helperFunction(arr);

  //return new array
  return newArr;
}

console.log(flatten([1, [2, [3, 4],
  [
    [5]
  ]
]]));

或者,为了更简洁,使用flat(为不兼容的浏览器添加一个polyfill):

const flatten = arr => arr.flat(Infinity);

console.log(flatten([1, [2, [3, 4],[[5]]]]));


推荐阅读