Javascript: How to recursively group arrays based upon upcoming index value -
i have situation want group arrays chunks based upon value of upcoming index. let's consider example
input
var tokens = [{     tag: null,     line: 'starting of file' }, {     tag: 'each',     line: null }, {     tag: null,     line: 'foo bar' }, {     tag: null,     line: 'baz' }, {     tag: 'endeach',     line: null }, {     tag: null,     line: 'hello world' }] expected output
[{     tag: null,     line: 'starting of file' }, {     tag: 'each',     line: null,     childs: [{         tag: null,         line: 'foo bar'     }, {         tag: null,         line: 'baz'     }] }, {     tag: null,     line: 'hello world' }] what happening elements after opening each tag nested childs. can happen recursively there can multiple each tags before endeach.
hope makes sense!
using array.prototype.reduce(), whenever encounter each add children array container array. whenever encounter endeach remove last array container. items push last array in container. in end 1st array in container include tree:
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 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);
Comments
Post a Comment