lodash源码分析每日一练 - 数组 - flatten / flattenDeep / flattenDepth

今日分享:

每一步都是曼妙的风景~

__.flatten(array)

使用:

减少一级array嵌套深度

使用示例:

js 复制代码
_.flatten([1, [2, [3, [4]], 5]]);
// => [1, 2, [3, [4]], 5]

尝试手写:

①修改原数组;②数组减少一级嵌套深度;③ 合并能力,可以减少n层嵌套深度

js 复制代码
    let flatten_arr=[1, [2,[3 ,[4]],5]];
    function my_flatten(arr) {
        if(arr.length === 0) { return arr };
        if(arr instanceof Array) {
            let newArr = [];
            for(let i = 0; i< arr.length; i++) {
                if(arr[i] instanceof Array) {
                    for(var j = 0; j < arr[i].length; j++) {
                        newArr.push(arr[i][j])
                    }
                }else{
                    newArr.push(arr[i])
                }
            }
            arr = newArr
        }
        return arr;
    }
    console.log(my_flatten(flatten_arr)); // [1,2,[3,[4]],5]

源码方案:

js 复制代码
function flatten(array) {
  var length = array == null ? 0 : array.length;
  return length ? baseFlatten(array, 1) : [];
}

function baseFlatten(array, depth, predicate, isStrict, result) {
  var index = -1,
      length = array.length;

  predicate || (predicate = isFlattenable);
  result || (result = []);

  while (++index < length) {
    var value = array[index];
    if (depth > 0 && predicate(value)) {
      if (depth > 1) {
        // 如果是多层级或直接拍平,递归调用自身即可完成
        baseFlatten(value, depth - 1, predicate, isStrict, result);
      } else {
        arrayPush(result, value);
      }
    } else if (!isStrict) {
      result[result.length] = value;
    }
  }
  return result;
}

类似方法

_.flattenDeep

将array递归为一维数组。

使用示例:

js 复制代码
_.flattenDeep([1, [2, [3, [4]], 5]]);
// => [1, 2, 3, 4, 5]

源码方案:

js 复制代码
function flattenDeep(array) {
  var length = array == null ? 0 : array.length;
  return length ? baseFlatten(array, INFINITY) : [];
}
_.flattenDepth

根据 depth 递归减少 array 的嵌套层级

使用示例:

js 复制代码
var array = [1, [2, [3, [4]], 5]];
 
_.flattenDepth(array, 1);
// => [1, 2, [3, [4]], 5]
 
_.flattenDepth(array, 2);
// => [1, 2, 3, [4], 5]

源码方案:

js 复制代码
function flattenDepth(array, depth) {
  var length = array == null ? 0 : array.length;
  if (!length) {
    return [];
  }
  depth = depth === undefined ? 1 : toInteger(depth);
  return baseFlatten(array, depth);
}

总结

总的来说还是循环+递归调用的方式,实现深层拍平。取值然后push到新数组即可。

相关推荐
cc_瀚海知行几秒前
工具调用 6|助手什么时候该停下来?
java·服务器·前端·人工智能·python·ai
想做小南娘,发现自己是女生喵5 分钟前
QT项目实战第一周(嵌入式)
开发语言·qt
学逆向的11 分钟前
C 可变量参数
c语言·开发语言·网络安全
andyweike12 分钟前
kotlin dsl library工程怎么配置
android·开发语言·kotlin
溪语流沙16 分钟前
【Web全栈进阶】Nginx反向代理 + HTTPS:正式上线
前端·vue.js·python·nginx·https·fastapi
huaweichenai18 分钟前
php搭建mcp服务
开发语言·php·ai编程
vivo互联网技术27 分钟前
域名埋点零侵入实时校验实践:基于代理转发与规则驱动的工具设计
前端·测试·监控·代理·埋点
喵个咪27 分钟前
GoWind ShortPlay 拆解:Flutter 沉浸式 Feed 的播放器工程——生命周期、手势状态机与游客降级
前端·flutter·架构
白日做梦Q28 分钟前
Chrome商店访问不了,无法现在安装插件?利用Edge商店迁移扩展完整实操教程问题背景
前端·chrome·edge