Javascript:如何根据即将到来的索引值递归地分组数组
Javascript: How to recursively group arrays based upon upcoming index value
我有一种情况,我想根据即将到来的索引的值将数组分组成块。让我们考虑这个例子
输入var tokens = [{
tag: null,
line: 'starting of the file'
},
{
tag: 'each',
line: null
}, {
tag: null,
line: 'foo bar'
}, {
tag: null,
line: 'baz'
}, {
tag: 'endeach',
line: null
}, {
tag: null,
line: 'hello world'
}]
预期输出
[{
tag: null,
line: 'starting of the file'
},
{
tag: 'each',
line: null,
childs: [{
tag: null,
line: 'foo bar'
}, {
tag: null,
line: 'baz'
}]
}, {
tag: null,
line: 'hello world'
}]
真正发生的是,在开始的each
标记之后的所有元素都嵌套为子元素。现在这也可以递归地发生,在endeach
之前可以有多个each
标签。
希望这是有意义的!
使用Array.prototype.reduce()
,每当遇到each
时,我们将子数组添加到container
数组中。每当遇到endeach
时,就从container
中删除最后一个数组。在container
中,我们总是将项压入最后一个数组。最后,container
中的第一个数组将包括树:
function fold(arr) {
return arr.reduce(function(container, item) {
if (item.tag === 'endeach') {
container.pop();
return container;
}
container[container.length - 1].push(item);
if (item.tag === 'each') {
item.children = [];
container.push(item.children);
}
return container;
}, [[]])[0];
}
var tokens = [{
tag: null,
line: 'starting of the file'
}, {
tag: 'each',
line: null
}, {
tag: null,
line: 'foo bar'
}, {
tag: 'each',
line: null
}, {
tag: null,
line: 'foo bar21'
}, {
tag: null,
line: 'baz21'
}, {
tag: 'endeach',
line: null
}, {
tag: 'each',
line: null
}, {
tag: null,
line: 'foo bar22'
}, {
tag: null,
line: 'baz22'
}, {
tag: 'endeach',
line: null
},{
tag: null,
line: 'baz'
}, {
tag: 'endeach',
line: null
}, {
tag: null,
line: 'hello world'
}
];
var result = fold(tokens);
console.log(result);
相关文章:
- 数组在递归方法中设置为null
- 具有嵌套对象数组的 Javascript 对象的递归搜索函数
- Javascript-用于展开数组的递归/for循环
- 递归布尔和/或到数组的jison解析器
- 给定一个带有数字的数组,我如何编写一个递归函数,当 2 个元素加起来为一个目标时,它会在数组中查找索引
- 异步循环使用递归:如何访问推送数组数据
- javascript递归,按数组位置查找子级
- 数组JavaScript中的递归串联字符串
- 简单数组递归而不是while
- 在数组上递归达到最大调用大小
- 在JavaScript中,从一组数组递归地构建一个字典/嵌套对象
- javascript中递归复制二维数组的算法
- 对象数组中的递归循环
- 我的 JavaScript 暴力递归数独求解器内存不足吗?
- Javascript 数组递归更改值
- 使用 jQuery 读取递归数组
- 递归数组反转Javascript
- 使用递归为数组中的每个项返回一个值
- 这个递归数组排列函数是如何工作的
- 用递归数组加载递归组件