Steve Medley Steve Medley - 4 months ago 7
Javascript Question

Picking more than one random from an array

I wrote this function:

function randomProduct(num) {
var iter = num;
for (var i = 0; i < iter; i++) {
var rand = recommendedProducts[Math.floor(Math.random() * recommendedProducts.length)];
return rand
}
}


Which is supposed to pull from the
recommendedProducts
array however many are needed when the function is called. So basically
randomProduct(1)
would pull 1 and
randomProduct(4)
would pull 4, etc.

However no matter what number I enter in there when I test is through the console, I always only get 1 array item returned.

console.log(randomProduct(1));
console.log(randomProduct(2));
console.log(randomProduct(3));
console.log(randomProduct(4));


What am I doing wrong?

Answer

try this:

function randomProduct(num) {
    var iter = num;
    var rand ="";
    for (var i = 0; i < iter; i++) {
    rand += recommendedProducts[Math.floor(Math.random() * recommendedProducts.length)];
    }
    return rand

 }

as @Steve Medley said the result expected to be string. so if recommendedProducts contains some string you should add this string in each iteration of loop to your result and return it after your loop has finished( also this is what i have understood from question)

Comments