我有一份员工名单(阵列),他们将得到以下奖励:
建筑工人= [
{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 ...),以便工人按优先级排序获得全额奖金:
谁有解决方案,并在绝望的2周内帮助我解决了问题。好伤心
答案 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);