C_K
C_K

Reputation: 1243

Add Array item to Array X times

I have a base array of 6 different words that represent game elements. Just wondering how I would multiply the number of instances of each word within the array.

var gameItem = [cattle, wood, stone, metal, grain, craft];

That is, say I want 10 instances of each word to be added to the array, how would I do that? Order isn't important as it'll be shuffled.

Upvotes: 0

Views: 1564

Answers (3)

Nir Alfasi
Nir Alfasi

Reputation: 53565

You can do:

var gameItem = ['cattle', 'wood', 'stone', 'metal', 'grain', 'craft'];
var doublearr = gameItem.concat(gameItem); //x2
gameItem = doublearr.concat(doublearr);//x4
gameItem = gameItem.concat(gameItem );//x8
gameItem = gameItem.concat(doublearr);//x10 
alert(gameItem);    

Concatenate the array to itself until you reach the closest ^2 (below - in our case 8 = 2^3) and then add the rest.

I posted this solution because you wrote in one of the comments that you hope for something that isn't performance intensive. But I agree with the others that it's more readable and easier to maintain a simple for-loop. So if you have only x10 - keep it simple.

Upvotes: 1

António Almeida
António Almeida

Reputation: 10127

Don't forget that your array doesn't work unless you define each of those variable. But as I understand, those are words, not vars. So the right array declaration is:

var newGameItem = ["cattle", "wood", "stone", "metal", "grain", "craft"]

To repeat that array 10 times, you can use a for loop and the array method concat().

var newGameItem = [];
for(var i=0 ; i<10 ; i++) {
    newGameItem = newGameItem.concat(gameItem);
}

> newGameItem : ["cattle", "wood", "stone", "metal", "grain", "craft", "cattle" ... ]

I don't know what is your idea for this, but, if you want to store a quantity of elements of those kinds, like, player has 1 cattle, 12 wood, 20 stone, etc ... You probably should have a better data structure, like this:

 var gameItem = {"cattle" : 1, "wood" : 12, "stone" : 20, "metal" : 0, "grain" : 0, "craft" : 0 };

So by doing gameItem.wood, you get the result > 12

Upvotes: 4

jfriend00
jfriend00

Reputation: 708206

You just need a couple loops:

function dupElements(arr, n) {
    for (var i = 0, len = arr.length; i < len; i++) {
        for (var j = 0; j < n; j++) {
            arr.push(arr[i]);
        }
    }
}

dupElements(gameItem, 10);

The outer loop cycles through the initial elements. The inner loop adds n copies of each.

Upvotes: 1

Related Questions