过滤阵列并减少

时间:2019-05-14 12:24:39

标签: javascript arrays filter reduce

我有一个数组,我想创建一个div,每个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 个答案:

答案 0 :(得分:3)

要按职业获取薪水,请首先应用过滤器,然后您可以从过滤后的数组中汇总薪水。

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'));

答案 1 :(得分:0)

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