[
{
"id": 1,
"name": "Бумага",
"children" :[
{
"id": 2,
"name": "Бумага офисная",
"children" :[
{
"id": 3,
"name": "Бумага для принтера"
},
{
"id": 4,
"name": "Бумага для цветная"
}
]
}
]
},
{
"id": 5,
"name": "Товары для офиса",
"children" :[
{
"id": 6,
"name": "Оборудование",
"children" :[
{
"id": 7,
"name": "Для досок"
},
{
"id": 8,
"name": "Бэйджики"
}
]
}
]
},
{
"id": 9,
"name": "Товары для школы",
"children" :[
{
"id": 10,
"name": "Подарки",
"children" :[
{
"id": 11,
"name": "Конфеты"
},
{
"id": 12,
"name": "Игрушки"
}
]
}
]
}
]
[
{
"id": 3,
"name": "Бумага для принтера"
},
{
"id": 4,
"name": "Бумага для цветная"
},
{
"id": 7,
"name": "Для досок"
},
{
"id": 8,
"name": "Бэйджики"
},
{
"id": 11,
"name": "Конфеты"
},
{
"id": 12,
"name": "Игрушки"
}
]
function getLeaves(tree) {
const result = [];
for (const stack = [...tree]; stack.length;) {
const n = stack.pop();
if (Array.isArray(n.children) && n.children.length) {
stack.push(...n.children);
} else {
result.push(n);
}
}
return result.reverse();
}
function getLeaves(tree) {
const result = [];
const stack = [];
for (let arr = tree, i = 0; i < arr.length || stack.length; i++) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else if (arr[i].children instanceof Array && arr[i].children.length) {
stack.push([ i, arr ]);
[ i, arr ] = [ -1, arr[i].children ];
} else {
result.push(arr[i]);
}
}
return result;
}
function getLeaves([...tree]) {
for (let i = 0; i < tree.length; i++) {
const c = tree[i].children;
if (c?.constructor === Array && c.length) {
tree.splice(i--, 1, ...c);
}
}
return tree;
}