Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Перебор вложенных массивов объектов (https://javascript.ru/forum/misc/75861-perebor-vlozhennykh-massivov-obektov.html)

Alexandroppolus 13.11.2018 21:00

Цитата:

Сообщение от j0hnik (Сообщение 498477)
Прямо таки любую?

цикл + рукотворный стек - вот тогда любую
каждую рекурсивную задачу можно переписать на цикл и стек, но будет мутный говнокод

рони 13.11.2018 21:02

Poznakomlus,
пост#8 в строке 13 поменяйте 29 на 1.

Epitough 13.11.2018 23:06

Извиняюсь, если это был глупый вопрос. Спасибо, пойду дальше разбираться :thanks:

Epitough 13.11.2018 23:08

Цитата:

Сообщение от Poznakomlus (Сообщение 498476)
спрашивается зачем здесь map(), reduce()? :dance:

Да я чисто для себя.

Vlasenko Fedor 14.11.2018 04:01

Цитата:

Сообщение от Alexandroppolus
но будет мутный говнокод

увы, бывает :( и от рекурсии не отказался :cray:
<script>
const graph = {
    value: 65,
    children: [{
        value: 15,
        children: [{
            value: 55,
            children: [{
                value: 85,
                children: [{
                    value: 66,
                    children: [{
                        value: 1
                    }, {
                        value: 21
                    }]
                }]
            }, {value: -30}]
        }]
    }, {
        value: -1
    }]
};

const tree = data => {
    let arr = [], cur
    while (data.children && (cur = data.children.pop())) {
        arr = arr.concat(tree(cur))
    }
    return arr.concat(data.value)
}
const arr = tree(graph)
document.write(`Min: ${Math.min(...arr)}, Max: ${Math.max(...arr)}`)

//var tree=function(a){for(var b=[],c;a.children&&(c=a.children.pop());)b=b.concat(tree(c));return b.concat(a.value)};
</script>

Epitough 18.11.2018 17:54

Я сделал нахождение среднего значение таким образом:
const average = (graph) => {
    return sum(graph) / count(graph);
};

const sum = (graph) => {
    return graph.children ? graph.children.map(sum).reduce((item1, item2) => item1 + item2, graph.value) : graph.value;
}

const count = (graph) => {
    return graph.children ? graph.children.map(count).reduce((item1, item2) => {
    return item2.value ? (item1++, item1) : item1 += item2;
    }, 1) : graph;
};

Можно ли сделать это одной функцией(один проход по дереву)?

Malleys 18.11.2018 19:39

function average({ value, children = [] }, result = { sum: 0, count: 0 }) {
	result.sum += value;
	result.count++;

	for(const child of children)
		average(child, result);

	return result.sum / result.count;
}


Часовой пояс GMT +3, время: 20:48.