2017-05-30 81 views
1

我唯一的數組:混合物(或排序)JS陣列

[0, 1, 2, 3, 4, 5, 6, 7, 8] 

陣列的數據的「第一半」是[0,1,2,3,4],第二個是[5,1 6,7,8]。現在

我應該得到這樣的事情(這是不是隨機混合)

[0, 5, 1, 6, 2, 7, 3, 8, 4] 

這是數據的兩列的數組。我應該把第一部分的數據放在第一列,第二部分放在第二列。

我試圖找到一個簡單的解決方案...感謝您的建議!

+0

是什麼*** ***一半在這種情況下? –

+0

請參閱https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array。 –

+0

@NinaScholz對不起,我的英文)在我的第一個例子array.length = 9,「半」是Math.ceil(array.length/2)=> 5 ... –

回答

3

可以使用Math.ceil由2

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8], c = 1 
 

 
var half = arr.splice(Math.ceil(arr.length/2)) 
 
half.forEach(e => (arr.splice(c, 0, e), c += 2)) 
 

 
console.log(arr)

+0

完美的解決方案。 –

1

圍捕號碼,然後循環第一部分,並添加從第二部分遞增計數器,每個元素嘗試以下split陣列中一半,使用map和內聯if語句

var array = [0,1,2,3,4,5,6,7,8] 
 
    var result = array.map(function(item,index){ 
 
     return (index%2 == 0) ? array[index/2] : array[Math.floor((index+array.length)/2)]; 
 
    }); 
 
    console.log(result);

+0

你可能希望'index >> 1'在這裏不是'index/2'。例如,你的筆記對python2有效,但JS會給你一個浮點數。 – georg

+0

我添加了一個代碼片段,索引/ 2給出floor(index/2),它是一個數字不是浮點數 –

+1

@AloïsdeLaComble現在增加一個數組長度1 ...結果出錯了 –

0

您可以計算索引並映射數組中的值。

(i >> 1) + ((i & 1) * ((a.length + 1) >> 1)) 
^^^^^^^^          take the half integer value 
      ^^^^^^       check for odd 
          ^^^^^^^^^^^^  adjust length 
         ^^^^^^^^^^^^^^^^^^^^ the half value of adjusted length 

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8], 
 
    result = array.map((_, i, a) => a[(i >> 1) + ((i & 1) * ((a.length + 1) >> 1))]); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }