const company = [{
name: "Mike",
salary: 500
},
[{
name: "John",
salary: 600
}],
[
[{
name: "Mary",
salary: 400,
}],
[
[
[
[{
name: "Alex",
salary: 450
}]
]
]
],
],
];
-
вы как-то попробовали решить это самостоятельно?– teran4 мар 2022 в 13:02
-
function counter(company) { let salaryAmount = 0; if (Array.isArray(company)) { for (let value of company) { if (typeof (value) === 'object' && value.salary) { let personSalary = value.salary; console.log(personSalary) } if (Array.isArray(value)) { counter(value); } } } } counter(company); Вроде получается достучаться до значений , но на этом все.– UnKnown4 мар 2022 в 13:08
Добавить комментарий
|
1 ответ
Попробуйте как вариант такое решение:
const company = [{
name: "Mike",
salary: 500
},
[{
name: "John",
salary: 600
}],
[
[{
name: "Mary",
salary: 400,
}],
[
[
[
[{
name: "Alex",
salary: 450
}],
[{
name: "Alex"
}]
]
]
],
],
];
const countSummarySalary = (branches) => {
let sum = 0;
if (Array.isArray(branches)) {
for (const branch of branches) {
sum += countSummarySalary(branch);
}
} else if (typeof branches === 'object') {
return branches.salary ?? 0;
}
return sum;
}
console.log(countSummarySalary(company));
-
1что-то обычно такие вещи из рекурсии результатом возвращают, а не внешнюю переменную используют– teran4 мар 2022 в 14:27
-