最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to merge and shuffle array of arrays - Stack Overflow

programmeradmin3浏览0评论

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();

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();
Share Improve this question edited Jul 16, 2013 at 15:25 000 27.3k10 gold badges74 silver badges103 bronze badges asked Oct 10, 2012 at 21:28 ΩmegaΩmega 43.7k35 gold badges142 silver badges212 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

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 -

  • How can I shuffle an array?
  • How to randomize (shuffle) a JavaScript array?
$.merge( a[0], b );
$.merge( a[2], b );

You do not need jQuery specific function to do this

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

"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;
});
发布评论

评论列表(0)

  1. 暂无评论