JS数组扁平化(flat)
需求:多维数组=>一维数组
let ary = [1, [2, [3, [4, 5]]], 6];
let str = JSON.stringify(ary);
第0种处理:直接的调用
arr_flat = arr.flat(Infinity);
第一种处理
ary = str.replace(/(\[\]))/g, '').split(',');
第二种处理
str = str.replace(/(\[\]))/g, '');
str = '[' + str + ']';
ary = JSON.parse(str);
第三种处理:递归处理
let result = [];
let fn = function(ary) {
for(let i = 0; i < ary.length; i++) }{
let item = ary[i];
if (Array.isArray(ary[i])){
fn(item);
} else {
result.push(item);
}
}
}
第四种处理:用 reduce 实现数组的 flat 方法
function flatten(ary) {
return ary.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? flatten(cur) : cur);
})
}
let ary = [1, 2, [3, 4], [5, [6, 7]]]
console.log(ary.MyFlat(Infinity))
第五种处理:扩展运算符
while (ary.some(Array.isArray)) {
ary = [].concat(...ary);
}
JS数组扁平化(flat)的更多相关文章
- JavaScript数组常用方法解析和深层次js数组扁平化
前言 数组作为在开发中常用的集合,除了for循环遍历以外,还有很多内置对象的方法,包括map,以及数组筛选元素filter等. 注:文章结尾处附深层次数组扁平化方法操作. 作为引用数据类型的一种,在处 ...
- JS: 数组扁平化
数组扁平化 什么是数组扁平化? 数组扁平化就是将一个多层嵌套的数组 (Arrary) 转化为只有一层. // 多层嵌套 [1, 2, [3, 4]] // 一层 [1, 2, 3, 4] 递归实现 思 ...
- js数组扁平化
看到一个有趣的题目: var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10]; 一个多维 ...
- js中数组扁平化处理
- js多维数组扁平化
数组扁平化,就是将多维数组碾平为一维数组,方便使用. 一:例如,一个二维数组 var arr = ['a', ['b', 2], ['c', 3, 'x']],将其扁平化: 1. 通过 apply ...
- js实现数组扁平化
数组扁平化的方式 什么是数组扁平化? 数组扁平化:指将一个多维数组转化为一个一维数组. 例:将下面数组扁平化处理. const arr = [1, [2, 3, [4, 5]]] // ---> ...
- js技巧-使用reduce实现更简洁的数组对象去重和数组扁平化
Array.prototype.reduce()方法介绍: 感性认识reduce累加器: const arr = [1, 2, 3, 4]; const reducer = (accumulator, ...
- JS数组专题1️⃣ ➖ 数组扁平化
一.什么是数组扁平化 扁平化,顾名思义就是减少复杂性装饰,使其事物本身更简洁.简单,突出主题. 数组扁平化,对着上面意思套也知道了,就是将一个复杂的嵌套多层的数组,一层一层的转化为层级较少或者只有一层 ...
- javascrip的数组扁平化
扁平化 数组的扁平化,就是将一个嵌套多层的数组 array (嵌套可以是任何层数)转换为只有一层的数组. 举个例子,假设有个名为 flatten 的函数可以做到数组扁平化,效果就会如下: var ar ...
随机推荐
- DApp是什么,DApp是必然趋势
DApp是什么,DApp是必然趋势 https://www.jianshu.com/p/dfe3098de0de Thehrdertheluck关注 12018.04.23 11:54:00字数 2 ...
- java 正则 replace 忽略大小写
String description = model.getDescription(); if (!"".equals(description)) { //replace(/\&l ...
- 1 linux性能优化之平均负载uptime
不知道onenote的笔记复制出来就是图片了...
- c# 字符串递归截取
private void button1_Click_1(object sender, EventArgs e) { string ex = neirong.Text; List<string& ...
- 【洛谷5537】【XR-3】系统设计(哈希_线段树上二分)
我好像国赛以后就再也没有写过 OI 相关的博客 qwq Upd: 这篇博客是 NOIP (现在叫 CSP 了)之前写的,但是咕到 CSP 以后快一个月才发表 -- 我最近这么咕怎么办啊 -- 题目 洛 ...
- UV数据与风速风向数据转换
package com.qr.util; import java.text.DecimalFormat; /** * //TODO UV数据与风速风向数据转换 */ public class UVAn ...
- JAVA如何实现中式排名和美式排名
根据公司需求,需要编写中式和美式排名算法,根据具体业务编写的,代码如下,看不懂留言,欢迎探讨,求高手指教更高效稳定的方法.private static int[] datas = {9,9,10,10 ...
- golang中,map作为函数参数是如何传递的
当你声明一个map的时候: m := make(map[int]int) 编译器会调用 runtime.makemap: // makemap implements a Go map creation ...
- Spring Boot 注解大全,真是太全了!
一.注解(annotations)列表 @SpringBootApplication:包含了@ComponentScan.@Configuration和@EnableAutoConfiguratio ...
- bootstrap-wizard向导插件的使用
引用文件 <link rel="stylesheet" href="bootstrap-wizard/bootstrap-wizard.css"> ...