刷 freecodecamp 的中级 JavaScript 到此
而在该题目中需要 flatten 的实现:

于是手刷:

function steamroller(arrs) {
  if (!arrs || !arrs.length) throw new ReferenceError();
  var arr = [];

  (function flatten (items) {
    items.forEach(function(item){
      if (item !== undefined && item !== null) {
        if (Array.isArray(item)) {
          arr.push(flatten(item));
        } else {
          arr.push(item);
        }
      }
    });
  }(arrs));

  arr = arr.filter(function(item){
    return item;
  });

  return arr;
}

steamroller([1, [2], [3, [[4]]]]);

UPDATE @ 2019-5-11 3:12 PM

function flatten(arr) {
  return arr.reduce((all, curr) => {
	if (Array.isArray(curr)) {
		return [...all, ...flatten(curr)]
	} else {
		return [...all, curr]
	}
  }, [])
}
//  flatten tree data 展开树形数据
function flattenTreeData(tree) {
  return tree.reduce((flatten, curr) => {
    flatten.push(curr);

    if (Array.isArray(curr.children) && curr.children.length) {
      flatten.push(...flattenTreeData(curr.children));
    }

    return flatten;
  }, []);
}

相关文章:

  • 2021-12-02
  • 2021-11-17
  • 2021-08-04
  • 2021-12-14
  • 2021-07-14
  • 2021-09-10
  • 2021-09-28
猜你喜欢
  • 2021-09-16
  • 2022-12-23
  • 2022-02-16
  • 2021-08-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案