0

const people = [{
    name: 'frank',
    age: 20,
    position: 'front-end-developer',
    value: 7
  },
  {
    name: 'craig',
    age: 27,
    position: 'back-end-developer',
    value: 7
  },
  {
    name: 'peter',
    age: 23,
    position: 'database-manager',
    value: 6
  },
  {
    name: 'andy',
    age: 29,
    position: 'full-stack-developer',
    value: 9
  }
];

const salaryGenerator = (person) => {
  return '$' + (person.value * 10 / 5 * 15 + 200)
};

const sentenceGenerator = (person) => {
  return person.name + ' is ' + person.age + ' who works as a ' + person.position
}

const userNameGenerator = (person, ) => {
  const randomWord = ['donec', 'pellentesque', 'facilisis', 'potenti']
  return person.name + (person.age * person.value + 300) + randomWord[Math.floor(Math.random() * randomWord.length)]

}

const salary = people.map(salaryGenerator)
const sentence = people.map(sentenceGenerator)
const userName = people.map(userNameGenerator)
console.log(salary)
console.log(sentence);
console.log(userName);

I want to give the username a meaningless word at the end which is in randomWord. I would like it to be like frank440donec and give each username a different meaningless word at the end, but it gives all the names a different meaningless word except for two which are assigned the same meaningless word.

pilchard
  • 12,414
  • 5
  • 11
  • 23
  • 3
    Well you've only got four random words, so there's a 25% chance for each word to be chosen each time the callback is invoked. – Pointy Nov 20 '21 at 17:43
  • When you get random number then you can delete that work from the `randomWord` array, then you will get unique element form that array, but you should have enough element into the `randomWord` array – DecPK Nov 20 '21 at 17:47

1 Answers1

0

If the aim is to randomly assign -- avoiding duplicates -- from a set of names, then a good solution is to shuffle the names...

// names must be at least the length of the people array
const names = ['donec', 'pellentesque', 'facilisis', 'potenti'];
shuffle(names);

const userNameGenerator = (person, index) => {
  const randomWord = names[index];
  const ageXValue = person.age*person.value+300;
  return `${person.name}${ageXValue}${randomWord}`;
}

// shuffle based on  https://stackoverflow.com/a/12646864/294949
function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    const temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}

const people = [{
    name: 'frank',
    age: 20,
    position: 'front-end-developer',
    value: 7
  },
  {
    name: 'craig',
    age: 27,
    position: 'back-end-developer',
    value: 7
  },
  {
    name: 'peter',
    age: 23,
    position: 'database-manager',
    value: 6
  },
  {
    name: 'andy',
    age: 29,
    position: 'full-stack-developer',
    value: 9
  }
];

console.log(people.map(userNameGenerator))
danh
  • 62,181
  • 10
  • 95
  • 136