gon freecss
gon freecss

Reputation: 3

How to get the minimum value of an array for each id

I have an exercise which requires listing an array by id of banks that contain the client with the lowest salary.

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

this function returns the lowest of the whole array, and the function below lists the banks but not the client of less associated salary. only shows:

 {1: "undefined [object Object]", 2: "undefined [object Object]", 3: 
"undefined [object Object]"}

Any idea how to solve it? Thanks in advance.

The desired result would be:

{1: 600, 2: 300, 3: 1000}

Upvotes: 0

Views: 30

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370659

You do need to use reduce as you're doing, but you don't want to add to the existing balance, if there is an existing balance - instead, reassign the current balance:

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;
  }, {})
);

Upvotes: 1

Related Questions