Group object array according to operation result

Asked

Viewed 60 times

0

I have an array of jobs, each job has an ID and a certain amount of hours to be done. What I have to do is group these works, in groups that do not exceed 8 hours worked. For example, with the following array

const arr = [
  {
    id: 1,
    hrs: 2,
  },
  {
    id: 2,
    hrs: 4,
  },
  {
    id: 3,
    hrs: 6,
  },
];

The result, grouped by the ids, is

[[1,3], [2]]

My biggest difficulty here is that adding the obj of ID 1 with the obj of ID 2 gives a set of jobs, since the hours are less than 8, but adding the ojb of ID 1 with the obj of ID 3 gives exact 8 hours, so this is the best group. Go through the entire array and see which is the best sum of hours to be grouped is what I’m not able to turn into code here.

So far, what I got was this, I make a reduce and first try to filter the already grouped Jobs, and then proceed. And then I start to get confused, you can see the confusion by the code. I try to create groups of sums and then abstract those that make more sense, but it seems very laborious and complex, I believe there is another way to do.

  • I don’t quite understand what the criterion is best group...

  • It is the one that comes closest to 8 hours of work, which is the limit for each group. Create a group with obj ID 1 and ID 3 is the best group because it will be exactly 8hrs of work, while adding id 1 with id 2 is 6 hours of work, leaving two hours 'idle', since you can not join the other job because it would pass 8hrs

  • You will always have 3 items in the array?

  • No, the amount of items will vary according to what is registered in the bank, then that took for me, create something that is smart enough to go through

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.