Home > Software engineering >  I dont know how to give each value of data from a variable to a value from another variable
I dont know how to give each value of data from a variable to a value from another variable

Time:11-22

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

CodePudding user response:

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))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related