Skip to content
Advertisement

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:

JavaScript

Then one picks a random job name like that:

JavaScript

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?

Advertisement

Answer

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.

JavaScript
JavaScript

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 …

JavaScript
JavaScript

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 …

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement