Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
How to give random unique role to all of my users in js?
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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda