У меня есть массив, и я хотел бы создать div, каждый с типом профессии и показать общую сумму зарплаты в каждой профессии.
Но у меня есть проблема, чтобы сделать функцию для этого, я не могу найти ошибку.
Я пытаюсь: let totalSum = array.filter(dep => dep.profession == name).map(filt => filt.salary).reduce((acc, score) => acc + score, 0);
но проблема в том, чтобы получить имя
Вот код:
let array = [
{name: Peter, profession: teacher, salary: 2000},
{name: Ana, profession: teacher, salary: 2000},
{name: Bob, profession: policeman, salary: 3000}]
function getDepartments(target, array) {
let keyArray = array.map(function (obj) {
for (let [key, value] of Object.entries(obj)) {
if (key === target) {
return value;
}
}
});
const createDepartments = function (array) {
let set = Array.from(new Set([...array]));
set.forEach(function (name) {
let chk = `<span>totala salary for profession ${name}:
//here I would like to put "total sum of salary" ${totalSum}
</span>`;
summary.lastElementChild.insertAdjacentHTML('beforeend', chk);
});
};
summary.insertAdjacentHTML('beforeend', `<div class="dataSummary"><span></span></fieldset>`)
createDepartments(keyArray);
}
getDepartments('profession', array);
Спасибо за помощь :)
Всего 2 ответа
Чтобы получить зарплату по профессии, сначала примените фильтр, а затем вы можете суммировать зарплату из отфильтрованного массива.
let input = [ {name: 'Peter', profession: 'teacher', salary: 2000}, {name: 'Ana', profession: 'teacher', salary: 2000}, {name: 'Bob', profession: 'policeman', salary: 3000} ]; function getSalaryByProfession(professionName) { return input.filter(({profession}) => profession == professionName) .reduce((accu, {salary}) => accu + salary , 0); } console.log(getSalaryByProfession('teacher'));
let input = [
{name: 'Peter', profession: 'teacher', salary: 2000},
{name: 'Ana', profession: 'teacher', salary: 2000},
{name: 'Bob', profession: 'policeman', salary: 3000}
];
function getSalaryByProfession(professionName) {
return input.filter(({profession}) => profession == professionName)
.reduce((accu, {salary}) => accu + salary , 0);
}
let const uniqueProfession = [];
input.forEach(o => {
if(!uniqueProfession.includes(o.profession)) {
uniqueProfession.push(o.profession);
getSalaryByProfession(o.profession);
// Write logic of creating div
}
})