1

Allo'

I'm working on a little project of mine and part of it involves taking a two dimensional array already created and randomizing it.

So I have something which looks like this:

foo = [[1,2],[3,4],[5,6],[7,8]];

randomizeFoo = function(){ 
    var randomizedFoo = [];
    newFoo = foo;
    for(i = 0; i < newFoo.length; i++){
        count = Math.random() * newFoo.length;
        randomizedFoo.push(newFoo.slice(count, count + 1));
    }
    return randomizedFoo; 
};

This does indeed randomize the array but I end up with something like this:

randomizedFoo = [[[7,8]],[[1,2]],[[5,6]],[[3,4]]]

My nice neat 2D array is now a 3D array with the lowest level arrays now burred under an extra level. I realize that this is not really that big a deal and the rest of my code just needs to compensate but it bugs me for 2 reasons:

  1. It's extra complexity and that's never good.
  2. I don't like my code doing things without me knowing the reason why.

Anybody have any ideas as to why it's doing this? I put a 2D array in, I want a 2D array back out again.

Jonathon Nordquist
  • 2,066
  • 4
  • 21
  • 23

2 Answers2

0

You can take the script from this answer and use map with it:

foo = range(0, foo.length-1, true).map(function(i) {
  return foo[i];
});

Demo: http://jsbin.com/ayepeh/1/edit (ctrl + enter to refresh)

Community
  • 1
  • 1
elclanrs
  • 92,861
  • 21
  • 134
  • 171
0

It's because you are using slice. Just use count as the index into foo. As in : randomizedFoo.push(foo[count]);

Make sure you make count an int first.

Cris Stringfellow
  • 3,714
  • 26
  • 48
  • This worked. After the randomizedFoo.push(foo[count]); I added a foo.splice(count, 1); to remove the value I'd pushed to the new array, otherwise I would get duplicates in the new array. Much obliged for the help, it would seem that I have more to learn about the splice method. – Jonathon Nordquist Jan 27 '13 at 18:58
  • No worries. There's always more to learn, probably! It seems that splice returns anything it finds inside an array, so your values, even if only a single entry long, will get wrapped in another array. – Cris Stringfellow Jan 27 '13 at 19:06