首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >过滤数组和归约

过滤数组和归约
EN

Stack Overflow用户
提问于 2019-05-14 20:24:39
回答 2查看 54关注 0票数 0

我有数组,我想创建div,每个职业类型,并显示每个职业的工资总额。

但是我有问题来做这个函数,我找不到错误。

我尝试过:let totalSum = array.filter(dep => dep.profession == name).map(filt => filt.salary).reduce((acc, score) => acc + score, 0);,但问题是获取名称

代码如下:

代码语言:javascript
复制
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);

感谢您的帮助:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-14 20:37:24

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

代码语言:javascript
复制
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'));

票数 3
EN

Stack Overflow用户

发布于 2019-05-14 20:52:52

代码语言:javascript
复制
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
     }         
})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56130453

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档