Ωmega
Ωmega

Reputation: 43683

How to merge and shuffle array of arrays

Having array of arrays

var a = [[[1, "alpha", "a"],
          [2, "beta",  "b"]],
         [[3, "gama",  "c"]],
         [[4, "delta", "d"]]];

var b = [];

1) How can I merge a[0] and a[2] into b?

2) How can I shuffle array b?


This is a shuffle algorithm I am using >>

Array.prototype.shuffle = function() {
  for (var i = 0; i < this.length; i++)
    this.push(this.splice(Math.random() * (this.length - i), 1)[0]);
  return this;
}

with syntax

myArray.shuffle();

Upvotes: 2

Views: 2518

Answers (4)

Shmiddty
Shmiddty

Reputation: 13967

"Shuffling" is pretty simple:

var arry = [0,1,2,3,4,5,6,7,8,9];
arry.sort(function(a,b){
    return Math.random() * 2-1;
});

Upvotes: 0

Joshua Wooward
Joshua Wooward

Reputation: 1508

You do not need jQuery specific function to do this

Look at http://w3schools.com/jsref/jsref_concat_array.asp

Upvotes: 1

David G
David G

Reputation: 96845

$.merge( a[0], b );
$.merge( a[2], b );

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79840

To merge you can simply use concat.

var b = a[0].concat(a[2]);

For shuffling you need to write your own shuffling logic. There is no API for such.

Shuffling -

Upvotes: 7

Related Questions