Tudor Apostol
Tudor Apostol

Reputation: 45

JavaScript function to returning array

I have the following code:

var disArray = ['red','red','green','green','green','blue','blue','blue','blue','blue'];
var otherArray = [];


function takeOut() {
    for ( i = 0; i < 3; i++ ) {
        var randItem = disArray[Math.floor(Math.random()*disArray.length)];
        otherArray.push(randItem);
    }
    return otherArray;
}

takeOut(disArray)
console.log(otherArray)

I want the function to return the elements in otherArray when it is called, but it I get the error undefined. It only works when I console.log otherArray. Is there any way that I can make the function return the array without using console.log?

Upvotes: 0

Views: 2874

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386868

You could use a local variable.

function takeOut() {
    var otherArray = [], i, randItem;
    for (i = 0; i < 3; i++ ) {
        randItem = disArray[Math.floor(Math.random() * disArray.length)];
        otherArray.push(randItem);
    }
    return otherArray;
}

var disArray = ['red','red','green','green','green','blue','blue','blue','blue','blue'],
    result = takeOut(disArray);

console.log(result);

For a reusable function, you could add some parameters to the function, like the array and the count, you need.

function takeOut(array, count) {
    var result = [];
    while (count--) {
        result.push(array[Math.floor(Math.random() * array.length)]);
    }
    return result;
}

var disArray = ['red','red','green','green','green','blue','blue','blue','blue','blue'],
    result = takeOut(disArray, 5);

console.log(result);

Example for calling takeOut multiple times and store the result in an array.

function takeOut(array, count) {
    var result = [];
    while (count--) {
        result.push(array[Math.floor(Math.random() * array.length)]);
    }
    return result;
}

var disArray = ['red','red','green','green','green','blue','blue','blue','blue','blue'],
    i = 7,
    result = []

while (i--) {
    result.push(takeOut(disArray, 5));
}

console.log(result);

Upvotes: 1

ajaykumar
ajaykumar

Reputation: 656

Basically a call to takeOut() is returning a value using a return. If you want to print on the console, you need to pass it to the console.log() fn. The other way is to assign the fn call ie. takeOut() to a variable and direct the variable to the console or use elsewhere.

var disArray = ['red','red','green','green','green','blue','blue','blue','blue','blue'];
var otherArray = [];


function takeOut() {
    for ( i = 0; i < 3; i++ ) {
        var randItem = disArray[Math.floor(Math.random()*disArray.length)];
        otherArray.push(randItem);
    }
    return otherArray;
}

takeOut()  //need to utilize the returned variable somewhere.
console.log(takeOut())  //prints to stackoverflow.com result // inspect browser console

Upvotes: 0

Related Questions