const role = [
{
name: 'Hitman'
},
{
name: 'Doctor'
},
{
name: 'Nurse'
}
]
This is my array of objects now this is my users
const user = ['James', 'Harden']
notice there are only two, so only two random roles will used from my array of objects now the result i want is
[
{
name: 'Hitman'
User: 'Harden'
},
{
name: 'Nurse'
User: 'James'
}
]
See, random user for a random role how can i do that?
Use this answer to Get a random item from a JavaScript array
Use Array.map to loop through your users and choose a random role for each.
const role = [{
name: 'Hitman'
},
{
name: 'Doctor'
},
{
name: 'Nurse'
}
];
const user = ['James', 'Harden'];
const users = user.map(name => ({
name: role[Math.floor(Math.random() * role.length)].name,
User: name
}));
console.log(users);
In order to do it uniquely, perform a random shuffle on the array, then assign the values sequentially...
// this thanks to https://stackoverflow.com/a/2450976/294949
function shuffle(array) {
let currentIndex = array.length, randomIndex;
while (currentIndex != 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]
];
}
return array;
}
let role = [{
name: 'Hitman'
},
{
name: 'Doctor'
},
{
name: 'Nurse'
}
];
shuffle(role); // when this is run, the role array is randomly reordered
const user = ['James', 'Harden', 'Curry', 'Thompson', 'Green'];
// assign roles sequentially, like dealing cards from the top of a shuffled deck
const usersWithRoles = user.map((user, index) => {
let roleName = index < role.length ? role[index].name : 'Hitman'
return { name: user, roleName };
});
console.log(usersWithRoles);
Another solution:
Since you want to prevent duplicate item from array, the best way is to copy the array and remove the specific item every time from the created array. This could keep the orignial data.
const role = [{ name: 'Hitman', img: 'hitman.png'},{ name: 'Doctor', img: 'doc.png'},{ name: 'Nurse', img: 'nurse.png'}]
const user = ['James', 'Harden', "Jason", "Iris"]
let test = []
let left = JSON.parse(JSON.stringify(role))
for (let i of user) {
if (left.length > 0) {
let ran = Math.floor(Math.random() * left.length)
test.push({ user: i,name: left[ran].name,img: left[ran].img})
left.splice(ran, 1)
} else {
test.push({user: i,name: "Hitman",img:'hitman.png'})
}
}
console.log(test)