Skip to content Skip to sidebar Skip to footer

Jquery Multidimensional Array Shuffle Random

I want to minimize my code from: myArrayA = [1, 2, 3, 4, 5]; fisherYates(myArrayA); myArrayB = [6, 7, 8, 9, 10]; fisherYates(myArrayB); myArrayC = [11, 12, 13, 14, 15]; fisherYates

Solution 1:

If you simply want to run an operation over all the elements in an array, then you should use map or forEach. I'm sure jquery provides shims for these methods in older browsers. So if we assume you're using your original fisherYates function unaltered, we might have something like this:

var multArr = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]];
multArr.forEach(fisherYates);

On accessing the elements, you're almost right, but you have one set too many of brackets :

multArr[1]; // == [6, 7, 8, 9, 10]multArr[1][3]; // == 9

I wouldn't speculate about the performance, if you're really worried you should put together a jsperf test case.

Solution 2:

All you need is jQuery's .each() method, like so:

$.each(multArr, function(i) { fisherYates(this) });

See console on

this working example

Fiddle Code

functionfisherYates(myArray) {
    var i = myArray.length, j, tempi, tempj;
    if (i === 0) returnfalse;
    while (--i) {
        j = Math.floor(Math.random() * (i + 1));
        tempi = myArray[i];
        tempj = myArray[j];
        myArray[i] = tempj;
        myArray[j] = tempi;
    }
}
$(function() {
    $("button").on("click", function(e) {
        multArr = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]];
        $.each(multArr, function(i) { fisherYates(this) });
        console.log(multArr)
    })
})

Solution 3:

Check out my code here. Basically just looped over the elements of the multidimensional array and run the fisherYates on them like so:

functionfisherYates(myArray) {
    for(var i = 0; i< myArray.length; i++) {
       k = myArray[i].length;
       while(k--){
            j = Math.floor(Math.random() * (myArray.length - 1));
            tempk = myArray[i][k];
            tempj = myArray[i][j];
            myArray[i][k] = tempj;
            myArray[i][j] = tempk;
       }
    }
}

Now if you wanted to do this for an n-dimensional array you're going to have to do it recursively, which would be fun, but I think that is more than you were asking for. If not I can update it later.

Post a Comment for "Jquery Multidimensional Array Shuffle Random"