Mikawa Ben
Mikawa Ben

Reputation: 76

pulling a random item from multiple arrays

I have 12 arrays named f1 to f12 each with five items. I want to randomly pull one item from each array and push these into the new array sm1.

var sm1 = [];

for (var i=1; i<=12; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push("f"+i[randomPrompt]);
}

However, this returns a random index of "f"+i instead of it indexing f1, f2, f3, f4, etc.

Upvotes: 0

Views: 237

Answers (5)

hirowaki
hirowaki

Reputation: 76

var sm1 = [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12].map(function (arr) {
    return arr[Math.floor((Math.random() * arr.length))];   
});

I'd vote using 2-d array instead of named 12 single arrays though.

Upvotes: 0

Ali Hesari
Ali Hesari

Reputation: 1939

There's a few ways to accomplish what you ask.

Example:

var myArray = {
   "f1": [1,2,3,4,5],
   "f2": [6,7,8,9,10],
   "f3": [11,12,13,14,15],
   "f4": [16,17,18,19,20]
}

var sm1 = [];
for (var i=1; i<=4; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push(myArray["f"+i][randomPrompt]);
}
console.log(sm1);

OR, If you are using code in the browser:

f1 = [1,2,3,4,5];
f2 = [6,7,8,9,10];
f3 = [11,12,13,14,15];
f4 = [16,17,18,19,20];

var sm1 = [];

for (var i=1; i<=4; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push(window["f"+i][randomPrompt]);
}
console.log(sm1);

Or use eval():

f1 = [1,2,3,4,5];
f2 = [6,7,8,9,10];
f3 = [11,12,13,14,15];
f4 = [16,17,18,19,20];

var sm1 = [],item;

for (var i=1; i<=4; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    item = eval(["f"+i][0]);
    sm1.push(item[randomPrompt]);
}
console.log(sm1);

Upvotes: 0

Jaspreet Singh
Jaspreet Singh

Reputation: 1762

Changes below line

sm1.push("f"+i[randomPrompt]);

to

sm1.push(eval("f"+i+"["+randomPrompt+"]"));

Upvotes: 1

Alexios Tsiaparas
Alexios Tsiaparas

Reputation: 910

You can use the window object.

var sm1 = [];

for (var i=1; i<=12; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push(window["f"+i][randomPrompt]);
}

Upvotes: 0

Nikhil Rajawat
Nikhil Rajawat

Reputation: 121

Why don't you use a 2-d array instead of 12 single arrays. Then it will be very easy.

Upvotes: 3

Related Questions