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

相关推荐
xieliyu.6 小时前
Java算法精讲:双指针(二)
java·开发语言·算法
云水一下7 小时前
TypeScript 从零基础到精通(五):高级类型与泛型
前端·javascript·typescript
何以解忧,唯有..7 小时前
Python包管理工具pip:从入门到精通
开发语言·python·pip
counterxing7 小时前
vibe coding 之后,我更不想打字了
前端·agent·ai编程
雪的季节7 小时前
RabbitMQ详解
开发语言
云水一下7 小时前
TypeScript 从零基础到精通(六):类型声明与模块化
javascript·typescript
copyer_xyf7 小时前
Python 模块与包的导入导出
前端·后端·python
研☆香7 小时前
es6新特性功能介绍(四)
前端·ecmascript·es6
微扬嘴角7 小时前
React篇1--JSX语法规则、组件、组件实例的3大特性
前端·react.js·前端框架
ice8130331818 小时前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib