Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

109
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda