过滤阵列并减少



我有数组,我想创建Divs,每种都有专业类型,并显示每个职业的总薪水总和。

但是我有问题要为此起作用,我找不到错误。

我尝试: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);

谢谢您的帮助:(

要按职业获得工资,首先应用过滤器,然后您可以从过滤的数组中总结工资。

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
     }         
})

最新更新