senfish / blog

个人技术博客
4 stars 0 forks source link

6. 实现一个flat函数,接收一个depth参数 #6

Open senfish opened 3 years ago

senfish commented 3 years ago

实现一个flat函数,扁平化数组,接收一个arr数组和一个depth参数,如果不传,默认为1;

function flat (arr, depth) {

}

flat([1,[2,3,[4,5]]], 2);  // [1,2,3,4,5]
flat([1,[2,3,[4,5]]]);  // [1,2,3,[4,5]]
senfish commented 3 years ago
function flat(arr, depth = 1) {
  return depth > 0 ?
    arr.reduce((pre, cur) => {
      return pre.concat(Array.isArray(cur) ? flat(cur, depth - 1) : cur);
    }, []) :
    arr.slice();
}
senfish commented 3 months ago
function flat(list, depth = 1) {
  let result = [];
  for(let i = 0; i < list.length; i++) {
    let value = list[i];
    if(Array.isArray(value) && depth > 0) {
      result = result.concat(flat(value, depth - 1))
    } else {
      result.push(value);
    }
  }
  return result;
}