2021-07-10 补全 flat 函数

flat([1, [2, 3, [4]], [5, 6]]) // 返回 [1,2,3,4,5,6]

const flat = (arr, count) => {
  let result = [];
  if(!Array.isArray(arr) || typeof count !== 'number') return result;
  if(count <= 0) return arr;
  let flag = true;
  arr.forEach(v => {
    if(Array.isArray(v)) {
      result.push(...v);
      flag = false;
    } else {
      result.push(v);
    }
  })
  if(!flag) {
    result = flat(result, count-1);
  }
  return result;
}

reduce简化版

const flat = (arr, count) => {
  if(!Array.isArray(arr)) {
    throw new Error('Must input a Array!!!');
  }
  return count > 0 ? arr.reduce((acc, cur) => acc.concat(
    Array.isArray(cur) ? flat(cur, count - 1) : cur
  ), []) : arr;
}

你可能感兴趣的:(2021-07-10 补全 flat 函数)