我有一个练习,要求按银行ID列出包含薪资最低的客户的银行阵列。
const bills = [
{ Idclient: 2, Idbank: 2, salary: 20000 },
{ Idclient: 3, Idbank: 1, salary: 600 },
{ Idclient: 1, Idbank: 3, salary: 3000 },
{ Idclient: 4, Idbank: 1, salary: 2000 },
{ Idclient: 6, Idbank: 2, salary: 300 },
{ Idclient: 5, Idbank: 3, salary: 2500 },
{ Idclient: 7, Idbank: 3, salary: 1000 },
];
function BankMinClient() {
var min = bills.reduce(function(prev, current) {
return (prev.Idclient > current.salary) ? prev : current
})
console.log(min)
let map = bills.reduce(function(map, bill) {
var bank_id = bill.Idbank;
var balance = +bill.salary;
map[bank_id] = (map[min]) + min
return map
}, {})
return map
};
BankMinClient();
此函数返回整个数组的最低值,下面的函数列出了银行,但没有列出薪水较低的客户。仅显示:
{1: "undefined [object Object]", 2: "undefined [object Object]", 3:
"undefined [object Object]"}
任何想法如何解决?预先感谢。
所需的结果将是:
{1: 600, 2: 300, 3: 1000}
答案 0 :(得分:1)
您确实需要使用reduce
,但是如果有余额,则不想添加到现有余额中,而是 reassign 当前余额:
const bills = [
{ Idclient: 2, Idbank: 2, salary: 20000 },
{ Idclient: 3, Idbank: 1, salary: 600 },
{ Idclient: 1, Idbank: 3, salary: 3000 },
{ Idclient: 4, Idbank: 1, salary: 2000 },
{ Idclient: 6, Idbank: 2, salary: 300 },
{ Idclient: 5, Idbank: 3, salary: 2500 },
{ Idclient: 7, Idbank: 3, salary: 1000 },
];
console.log(
bills.reduce((a, { Idbank, salary }) => {
const currentBalance = a[Idbank];
if (currentBalance === undefined || salary < currentBalance) {
a[Idbank] = salary;
}
return a;
}, {})
);