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

相关推荐
IT_陈寒3 分钟前
5个Java 21新特性实战技巧,让你的代码性能飙升200%!
前端·人工智能·后端
咖啡の猫5 分钟前
Vue内置指令与自定义指令
前端·javascript·vue.js
昔人'11 分钟前
使用css `focus-visible` 改善用户体验
前端·css·ux
前端双越老师14 分钟前
译: 构建高效 AI Agent 智能体
前端·node.js·agent
进击的圆儿17 分钟前
高并发内存池项目开发记录 - 02
开发语言·c++·实战·项目·内存池
xingxing_F22 分钟前
Swift Publisher for Mac 版面设计和编辑工具
开发语言·macos·swift
艾小码23 分钟前
告别数据混乱!掌握JSON与内置对象,让你的JS代码更专业
前端·javascript
你才是向阳花25 分钟前
如何用python来做小游戏
开发语言·python·pygame
夜晚中的人海28 分钟前
【C++】使用双指针算法习题
开发语言·c++·算法
怀旧,30 分钟前
【Linux系统编程】3. Linux基本指令(下)
linux·开发语言·c++