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

129
Visualizações
How can one access the related item from a 2nd array if one just has the randomly chosen item of the first array?

Basically, I have two arrays of related array items, where one item is/got randomly chosen.

I want to print the related item of the 2nd array. Let's say one has an array of job names, and it looks like this:

const jobNames = ["Builder", "Doctor", "Vet"];

Then one picks a random job name like that:

var randomJobName = jobNames[ Math.floor(Math.random() * jobNames.length) ];

Now one has another array which, with each item, features the description of its related job name.

How can one access the related item from the 2nd array if one just has the randomly chosen item of the first array?

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

0

If the job names and job descriptions are coupled together, I am wondering why they are in two different arrays at all. This is a perfect use case for Objects. I would structure it like this

const jobs = [
  {name: "Builder", description: "Builds Stuff"},
  {name: "Doctor", description: "Heals Stuff"},
  {name: "Vet", description: "Heals Stuff but for animals."}
]

Using object destructuring to access values:

const {name, description} = jobs[Math.floor(Math.random() * jobNames.length)]
alert(`Found job: ${name} who ${description}`)
about 4 years ago · Juan Pablo Isaza Relatório

0

There are basically 3 different approaches.

The easiest one is, as already suggested by VLAZ, to get a random index once and access both items each from its array by this random index.

const jobNames = ['Builder', 'Doctor', 'Vet'];
const jobDescriptions = [
  'creates/builds things/stuff.',
  'tries fixing human health issues.',
  'does fix animal health issues.',
];
const randomIdx = Math.floor(Math.random() * jobNames.length);

const jobName = jobNames[randomIdx];
const jobDescription = jobDescriptions[randomIdx];

console.log({ jobName, jobDescription });
.as-console-wrapper { min-height: 100%!important; top: 0; }

In case the OP has not the chance of using a single random index at time, and thus is forced to work with the already randomly picked job name, then the OP needs to find the index of this very job name from where the OP then can proceed with picking the related job description ...

const jobNames = ['Builder', 'Doctor', 'Vet'];
const jobDescriptions = [
  'creates/builds things/stuff.',
  'tries fixing human health issues.',
  'does fix animal health issues.',
];
// OP has no control about how `jobName` is/was/gets chosen.
const jobName = jobNames[ Math.floor(Math.random() * jobNames.length) ];

const index = jobNames.indexOf(jobName);
const jobDescription = jobDescriptions[index];

console.log({ jobName, jobDescription });
.as-console-wrapper { min-height: 100%!important; top: 0; }

In case such a task has to be run often/repeatedly and in case the OP can change code as the OP is pleased an approach was to combine both arrays into an array of aggregated job items (name and description) and make the random pick once from this new array structure ...

const jobNames = ['Builder', 'Doctor', 'Vet'];
const jobDescriptions = [
  'creates/builds things/stuff.',
  'tries fixing human health issues.',
  'does fix animal health issues.',
];
const jobList = jobNames
  .map(function (name, idx) {

    const description = this[idx];
    return {
      name,
      description,
    };
                        // `jobDescriptions` applied as
  }, jobDescriptions);  // `map`'s 2nd `thisArg` argument.

function getRandomArrayIndex(arr) {
  return Math.floor(Math.random() * arr.length);
}

const {
  name,
  description,
} = jobList[ getRandomArrayIndex(jobList) ];

console.log({ name, description });
console.log({ jobList });
.as-console-wrapper { min-height: 100%!important; top: 0; }

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