遍历嵌套的Javascript数组以创建路径
Traverse nested Javascript arrays to create paths
我有一个像这样的任意嵌套的数据结构-
var nested = [ 'a', [ [ 'b' ], [ 'c' ] ] ];
我想遍历这些级别来创建一个像这样的阵列阵列
var paths = [['a', 'b'] ['a', 'c']];
我知道这需要递归。有什么想法吗?!
这个问题有点模糊,但这里有一个有趣的函数,它取自对象扫描,您可以根据需要进行修改。
请注意,对输入的一些假设是,您没有指定
const iterate = (tree, cb) => {
const stack = [tree];
const parent = [null];
const count = [];
const depth = [];
const path = [];
let idx = 0;
let inc = true;
while (idx !== -1) {
const e = stack[idx];
if (e instanceof Set) {
stack[idx] = [...e];
stack[idx].or = true;
} else if (Array.isArray(e)) {
if (e.or !== true) {
stack.splice(idx, 1, ...e);
parent.splice(idx, 1, ...new Array(e.length).fill(parent[idx]));
if (parent[idx] !== null) {
depth[parent[idx]] += e.length - 1;
}
} else {
if (count[idx] === undefined) {
count[idx] = 0;
depth[idx] = 0;
} else if (depth[idx] !== 0) {
stack.splice(idx + 1, depth[idx]);
parent.splice(idx + 1, depth[idx]);
depth[idx] = 0;
}
if (count[idx] < e.length) {
stack.splice(idx + 1, 0, e[count[idx]]);
parent.splice(idx + 1, 0, idx);
count[idx] = (count[idx] || 0) + 1;
depth[idx] += 1;
inc = true;
idx += 1;
} else {
count[idx] = 0;
idx -= 1;
}
}
} else if (inc === true) {
path.push(e);
cb('ADD', e);
if (idx === stack.length - 1) {
cb('FIN', path);
inc = false;
} else {
idx += 1;
}
} else {
cb('RM', path.pop());
idx -= 1;
}
}
};
const extract = (tree) => {
const result = [];
iterate(tree, (type, p) => {
if (type === 'FIN') {
result.push([...p]);
}
});
return result;
};
console.log(extract(['a', new Set([['b'], ['c']])]));
// => [ [ 'a', 'b' ], [ 'a', 'c' ] ]
console.log(extract(['a', new Set([['b', new Set(['d', 'e'])], ['c']])]));
// => [ [ 'a', 'b', 'd' ], [ 'a', 'b', 'e' ], [ 'a', 'c' ] ]
console.log(extract(['a', new Set([['b'], ['c']]), 'd']));
// => [ [ 'a', 'b', 'd' ], [ 'a', 'c', 'd' ] ]
.as-console-wrapper {max-height: 100% !important; top: 0}
相关文章:
- 创建动画路径
- 如何在地图上创建路径叠加
- 遍历嵌套的Javascript数组以创建路径
- 如何在HTML中创建一个信息框,显示与悬停SVG路径相关的信息
- 创建从一个位置到另一个位置的路径动画
- 如何从输入到url的路径创建html文件
- Native Phonegap、下载并创建文件、动态命名文件和返回路径
- 如何创建一个浏览按钮,通过该按钮我可以选择系统的任何路径,即C:Program Files.并将其放入文本框中
- 给定一个对象数组,创建一个函数,该函数返回一个 Object,该 Object 具有按类型分组的路径数组
- 如何递归树并创建父路径节点数组
- 如何在 d3 和 SVG 中创建着色路径
- 正确填充 D3 创建的增强 svg 路径
- Rails:我可以将GET请求发送到创建路径吗?
- 织物.js - 在新创建的路径上实现形状识别
- 创建独立于平台的路径字符串
- 我应该如何在 Angular ui 路由器中创建模板网址属性的路径
- 为什么纸张.js路径创建在 iOS 设备上不起作用
- 寻路:如何为路径算法创建路径数据
- 如何创建路径与点符号从对象
- 从像斑点一样的图像的(内部和外部)边缘创建路径