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到新数组即可。

相关推荐
tachibana234 分钟前
与其他语言相比,使用 Go 有什么好处?
开发语言·后端·golang·go
阿俊-全栈开发5 小时前
LikeShop 单商户SaaS商城分销模块二开:佣金计算与结算逻辑实现
java·开发语言·微服务·likeshop·likeshop开源商城·likeshop多商户
奕鼎竜瑆7 小时前
Solid 前端响应式开发从零到精通
前端·人工智能
动恰客流统计7 小时前
景区客流统计怎么做?兼顾管控与运营的实施方案解析
大数据·前端·人工智能
派小心.8 小时前
A/B测试工具免费版够用吗?
前端·数据分析
m0_380743878 小时前
C++中的freopen的用法实例详解
开发语言·c++
前端snow8 小时前
ai agent --- redis 缓存
前端
Escalating_xu9 小时前
【Python】基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
jimy19 小时前
polymorph.cpp里面的“析构函数、智能指针”问题
开发语言·c++
m0_380743879 小时前
PHP 8.3 缓存清除不生效怎么排查
开发语言·php