Home > front end >  Randomly Select number of dictionary entries that are within categories?
Randomly Select number of dictionary entries that are within categories?

Time:12-20

So I managed to generate a "scoreboard" dictionary:

{
Player1: '10 1st',
Player2: '10 1st',
Player3: '10 1st',
Player4: '10 1st',
Player5: '10 1st',
Player6: '8 2nd',
Player7: '8 2nd',
Player8: '8 2nd',
Player9: '8 2nd',
Player10: '5 3rd',
Player11: '5 3rd',
Player12: '5 3rd'
}

But now I am not sure how to check if 1st/2nd/3rd in key string then randomly select certain number of entries from each "categories (1st,2nd,3rd)" in order to output a new dictionary such as:

If I want to randomly select 3 1st, 2 2nd and 3rd entries, the new dictionary will be

{
Player2: '10 1st',
Player4: '10 1st',
Player5: '10 1st',
Player6: '8 2nd',
Player9: '8 2nd',
Player11: '5 3rd',
Player12: '5 3rd'
}

Thanks for reading..

CodePudding user response:

Maybe convert the object to a randomized array of entries and then filter out separate arrays for each type with <Array>.filter, then use <Array>.slice on each array to get x amount of entries from it, and then reconstruct the object with the updated entries:

Example using numFirst = 3, numSecond = 2, numThird = 2:

const data = {
Player1: '10 1st',
Player2: '10 1st',
Player3: '10 1st',
Player4: '10 1st',
Player5: '10 1st',
Player6: '8 2nd',
Player7: '8 2nd',
Player8: '8 2nd',
Player9: '8 2nd',
Player10: '5 3rd',
Player11: '5 3rd',
Player12: '5 3rd'
}

let numFirst = 3;
let numSecond = 2;
let numThird = 2;

const entries = Object.entries(data).sort(() => .5 - Math.random());
const first = entries.filter(a => a[1].endsWith('1st')).slice(0, numFirst);
const second = entries.filter(a => a[1].endsWith('2nd')).slice(0, numSecond);
const third = entries.filter(a => a[1].endsWith('3rd')).slice(0, numThird);

const filteredData = Object.fromEntries([...first, ...second, ...third]);
console.log(filteredData);

  • Related