javascript - 如何仅展平/减少第 N 维数组的最深或其他指定级别
问题描述
假设一个 N 维数组,例如。
const array = [
"1",
["2","2"],
[["3","3"],["3","3"]],
[
[
[["4","4"],"3"],
[["4","4"],"3"]
],
],
[["3","3"],["3","3"]],
["2","2"],
"1"
];
我只能找到从索引的浅端向上展平数组的方法,但我需要展平/减少或仅处理最深(或任何任意)索引级别。
当运行最深的级别时,我正在寻找一个数组输出沿线的东西
array = [
"1",
["2","2"],
[["3","3"],["3","3"]],
[
[
["4,4","3"],
["4,4","3"]
],
],
[["3","3"],["3","3"]],
["2","2"],
"1"
];
我找不到不是垃圾的解决方案......(过于复杂/令人难以置信的混乱)任何帮助将不胜感激
解决方案
You could create a function that will take the data and level that you want to flatten and will flatten only that level. Then to get the last level you can create another function.
const array = ["1",["2","2"],[["3","3"],["3","3"]],[[[["4","4"],"3"],[["4","4"],"3"]],[["",""],["",""]]],[["3","3"],["3","3"]],["2","2"],"1"];
function lastLvl(data, lvl = 0) {
return data.reduce((r, e) => {
if (lvl > r) r = lvl
if (Array.isArray(e)) {
const nlvl = lastLvl(e, lvl + 1);
if (nlvl > r) r = nlvl
}
return r
}, 0)
}
function flattenLvl(data, lvl, clvl = 1) {
return data.reduce((r, e) => {
if (Array.isArray(e)) {
const nested = flattenLvl(e, lvl, clvl + 1);
if (clvl == lvl) r.push(...nested);
else r.push(nested)
} else {
r.push(e)
}
return r;
}, [])
}
const lvl = lastLvl(array)
const result = flattenLvl(array, lvl)
console.log(result)
推荐阅读
- javascript - Slick Slider 在网站上不起作用?
- python - Pyinstaller:如何进行特定的模块导入?
- r - 为什么按钮的observeEvent被错误触发(第二次)?
- python - 在keras,tensorflow中连接两层
- sql - 无法编写 sql 查询来查找一个月内的平均支付金额(考虑到时间段)
- html - Favicon 未显示
- javascript - 确保您正在运行一个打包服务器或在您的应用程序包中包含一个 .jsbundle 文件。(错误显示正在运行已经构建的项目)
- python - python对ec2实例列表进行排序
- avro - 如何在多个项目之间管理其 avro 模式?
- docker - 如何修复 docker 网络超时?