I'm trying to evenly distribute several people to different events. For example:
People Events John 10.10.2021 (4 people needed) Jack 11.10.2021 (2 people needed) Harry 12.10.2021 (1 people needed) Charlie 13.10.2021 (3 people needed) Jacob 14.10.2021 (5 people needed)
I want it, so that always the amount of people needed get assigned to the event. In the best case, every person gets assigned the same amount of times.
How can I achieve this in javascript / typescript?
CodePudding user response:
You could use map()
to loop through events and add people to them by slicing
the array of people. You could add logic for them to be separated evenly.
const people = ["John", "Jack", "Harry", "Charlie", "Jacob"];
const events = [{
date: "10.10.2021",
numPeople: 4
}, {
date: "11.10.2021",
numPeople: 2
}, {
date: "12.10.2021",
numPeople: 1
}, {
date: "13.10.2021",
numPeople: 3
}, {
date: "14.10.2021",
numPeople: 5
}];
const result = events.map((e) => {
return {
...e,
people: people.slice(0, e.numPeople)
}
});
console.log(result);
CodePudding user response:
Like this maybe:
const people = ['John', 'Jack', 'Harry', 'Charlie', 'Jacob']
const events = [{date: '10.10.2021', nr: 4}, {date: '11.10.2021', nr: 2},
{date: '12.10.2021', nr: 1}, {date: '13.10.2021', nr: 3}, {date: '14.10.2021', nr: 5}]
const ppl = []
people.forEach(p => ppl.push({'name': p, 'assigned': 0}))
const arr = []
events.forEach(e => {
let ex = {[e.date]: []}
arr.push(ex)
for(let i = 0; i < e.nr; i ) {
let min = Math.min(...ppl.map(p => p.assigned))
let pe = ppl.filter(p => p.assigned === min)
ex[e.date].push(pe[0].name)
pe[0].assigned
}
})
console.log(...arr)