分配奖金

时间:2019-06-10 03:33:30

标签: javascript arrays node.js

我有一份员工名单(阵列),他们将得到以下奖励:

  • 建筑工人= [ {name: "John", prize: 1000, prioritize: 1}, {name: "Andy", prize: 2000, prioritize: 2}, {name: "Bill", prize: 2200, prioritize: 3}, {name: :Carry", prize: 3100, prioritize: 4}, {name: "Asawa", prize: 4000, prioritize: 5} ]; //(数组Worker是不固定的...)

  • Let TotalPrize = 7100 //基金奖金

问题:我想在上面的列表中减去TotalPrize(1-> 2-> 3 ...),以便工人按优先级排序获得全额奖金:

  • John:1000(完整)
  • Andy:2000(完整)
  • 账单:2200(完整)
  • 运载:1900(在上面的列表中,“进位”必须为3100,但是因为对于剩余的前三个1900,TotalPrize = 7100已被预先分配)
  • 浅泽:0(因为前4个人的钱都被分割了)

谁有解决方案,并在绝望的2周内帮助我解决了问题。好伤心

1 个答案:

答案 0 :(得分:-1)

请检查以下代码,希望对您有帮助

let totalPrize = 7100;

const workers = [
    {
      name: "John",
      prize: 1000,
      prioritize: 1
    }, {
      name: "Andy",
      prize: 2000,
      prioritize: 2
    }, {
      name: "Bill",
      prize: 2200,
      prioritize: 3
    }, {
      name: "Carry",
      prize: 3100,
      prioritize: 4
    }, {
      name: "Asawa",
      prize: 4000,
      prioritize: 5
    }
  ];

const sortedWorkers = workers.sort((obj1, obj2) => obj1.prioritize > obj2.prioritize);

let finalResult = [];

sortedWorkers.map(worker => {
  if (totalPrize >= worker.prize) {
    finalResult.push({
      [worker.name]: worker.prize,
    });
    totalPrize -= worker.prize;
  } else {
    finalResult.push({
      [worker.name]: 0,
    });
  }
});

console.log(finalResult);