0

I'd like to take a random array from a 2D named array but all solution I tried didn't work maybe someone could help

var sites = [];

sites['apple'] = [
'green'
,
'red'
,
'blue'
];

sites['orange'] = [
'yellow'
];

There is more and of course not these names and the number is not fix and I'd like to take one random array. (Not item !)

Is it possible ?

3
  • 2
    Arrays don't use string keys, if that's the structure you want you should use a regular object for the outer "array" instead. Commented Mar 31, 2021 at 22:41
  • You are supposed to show what you have tried to do, and we ar supposed to help you to make your code better, not to give you a free code Commented Mar 31, 2021 at 22:45
  • @JohnMontgomery Yeah perfectly what I desired thank you. Commented Apr 1, 2021 at 0:26

1 Answer 1

0

Solution is :

var sites = [];

sites['apple'] = [
'green'
,
'red'
,
'blue'
];

sites['orange'] = [
'yellow'
];

var s_Array = Object.keys(sites);
var randomNumber = Math.random();
var s_Index  = Math.floor(randomNumber * s_Array.length);
var randomKey = s_Array[s_Index];
var randomsiteskey = sites[randomKey];

Check Pick random property from a Javascript object as @John Montgomery mentionned it

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.