JS flatten 简单实现

刷 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;
  }, []);
}
posted @ 2018-01-29 12:01  月光宝盒造梦师  阅读(1020)  评论(0编辑  收藏  举报