惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

静水深流's blog

探索 SSE:服务器推送技术的魅力与应用 | 静水深流 图解DIFF算法介绍 | 静水深流 如何使用javascript实现复制出的文案带链接? | 静水深流 基于vuepress2搭建专属自己的博客,并集成各种常用功能 | 静水深流 听说你至今不晓得缓存淘汰算法?实现LRU、LFU和FIFO? | 静水深流 最长递增子序列及vue3.0中diff算法 | 静水深流 二进制之入门到应用实践 | 静水深流 常见算法学习 | 静水深流 CSS 形状的实现 | 静水深流 ajax取消接口请求 | 静水深流 前端常见的安全问题 | 静水深流 关于http服务端的学习&总结 | 静水深流 前端面试题总结 | 静水深流 javascript原生代码实现及代码总结 | 静水深流 LeetCode算法学习总结-简单 | 静水深流 LeetCode算法学习总结-困难 | 静水深流 LeetCode算法学习总结- 中等 | 静水深流 排序算法总结 | 静水深流 扫码登录的实现原理 | 静水深流 Javascript之常见类型判断汇总 | 静水深流 JavaScript各种继承方式和优缺点 | 静水深流 webpack开发、使用及优化总结 | 静水深流 从JavaScript中的拷贝开始思考 | 静水深流 vue原理、使用及面试方面的总结 | 静水深流 前端发展及选择 | 静水深流 css面试总结 | 静水深流 文章列表 | 静水深流 首页 | 静水深流 学习网站收藏 | 静水深流
JavaScript 数组展开(扁平化)和underscore的 flatten | 静水深流
2020-09-21 · via 静水深流's blog

数组展开就是将嵌套的数组扁平化(转换为一维的)eg:

const arr=[[[1, 2], [1, 2, 3]], [1, 2]] => [1, 2, 1, 2, 3, 1, 2] 
console.log(flatten(arr))  //[1,2,1,2,3,1,2]

1、判断每一项是否是数组,然后递归

const arr=[[[1, 2], [1, 2, 3,"a"]], [1, 2,"a"]]
function flatten(arr){
    let result=[]
    for(let i=0,l=arr.length;i<l;i++){
        if(Array.isArray(arr[i])){
            //递归调用
            result=result.concat(flatten(arr[i]))  
        }else{
            result.push(arr[i])
        }
    }
    return result
}
console.log(flatten(arr),arr)

2、toString

数组在调用toString()会将数组转换成"1,2,1,2,3,1,2",再执行split(",")方法会变成["1", "2", "1", "2", "3", "1", "2"] 还需要将所有的参数转换为数字,所以这种方式的不足就是如果数组里面是[1,2,3,"4","5"]既有数字又有字符串,会全部展开为数字

const arr=[[[1, 2], [1, 2, 3]], [1, 2]]
function flatten(arr){
    return arr.toString().split(",").map(item => {
        //转为数字
        return +item
    })
}
console.log(flatten(arr),arr)

3、reduce方法

const arr=[[[1, 2], [1, 2, 3,"a"]], [1, 2,"b"]]
function flatten(arr){
    return arr.reduce((pre,next) => {
        return pre.concat(Array.isArray(next) ? flatten(next) : next)  //如果是数组同样的递归调用
    },[])
}
console.log(flatten(arr),arr)

4、解构的方式

利用es6新增结构方法可以提取一层的方法,来一层层提取出来

const arr=[[[1, 2], [1, 2, 3,"a"]], [1, 2,"b"]]
function flatten(arr){
    while(arr.some(item => Array.isArray(item))){
        //如果当前数组中还有数组,则展开
        arr=[].concat(...arr)
    }
    return arr
}
console.log(flatten(arr),arr)

5、js原生方法flat

flat(depth) 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。参数depth表示要提取嵌套数组的结构深度,默认为1

const arr=[[[1, 2], [1, 2, 3,"a"]], [1, 2,"b"]]
arr.flat(Infinity)

5、不用递归、MDN上的方式

// 不使用递归,使用 stack 无限反嵌套多层嵌套数组
function flatten(input) {
  const stack = [...input];
  const res = [];
  while (stack.length) {
    // 使用 pop 从 stack 中取出并移除值
    const next = stack.pop();
    if (Array.isArray(next)) {
      // 使用 push 送回内层数组中的元素,不会改动原始输入 original input
      stack.push(...next);
    } else {
      res.push(next);
    }
  }
  // 使用 reverse 恢复原数组的顺序
  return res.reverse();
}

6、Underscore.js的flatten方法

先上代码

/**
 * param {Array} input 要操作的数组
 * param {Boolean} shallow 浅展开,及为true时,只展开一层,为false是深度展开
 * param {Boolean} strict 遍历第一层时,是否放弃非数组对象
 * param {Array} output 保存最后输出的内容
 */
var flatten = function(input, shallow, strict, output = []) {
  var idx = output.length;
  for (var i = 0, length = getLength(input); i < length; i++) {
    var value = input[i];
    // 说明flatten方法对类数组对象也有支持
    if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
      if (shallow) {
        // 只展开一层
        var j = 0, len = value.length;
        while (j < len) output[idx++] = value[j++];
      } else {
        // 深度迭代,递归展开
        flatten(value, shallow, strict, output);
        idx = output.length;
      }
    } else if (!strict) {
      output[idx++] = value;
    }
  }
  return output;
};

output将返回数组当作参数传递,可以省去在递归的时候将数据一层层的return到上一层,在性能上会有所提升

注意

shallowfalse时,stricttrue是,返回的永远时[] ,这是因为,当shallowfalse时是深度迭代,,当最后迭代到不是数组的时候,就会进入到else if中,如果此时stricttrue则就不会进入到这个分支中,那么output就永远不会被操作,