简体   繁体   中英

filter array and reduce

I have array and I would like to create divs, each with profession type and show total sum of salary in every profession.

But I have problem to make function for this, I cannot find the mistake.

I try: let totalSum = array.filter(dep => dep.profession == name).map(filt => filt.salary).reduce((acc, score) => acc + score, 0); but problem is to get name

Here code:

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

Thank you for help :)

To get the salary by profession, first apply the filter and then you can sum up the salary from the filtered 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
     }         
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM