2017-02-03 12 views
-1

私は速度を含むマップポイントの配列を持っており、25ポイントごとに新しい配列を作成し、それらをチャンクと呼ばれる別の配列に挿入します。だから、これは私がやっているものです:配列のチャンクをJavaScript内の別の配列にプッシュ

var chunks = []; // the array of chunks 
var tempArray = []; //used for storing current chunk 
var currentLoop = 0; //used for checking how many items have been taken 
for (var i = 0; i < gon.map_points.length; i++) { 
    if (currentLoop == 26) { // if the current items stored is above 25 
     chunks.push(tempArray); // push the chunk 
     currentLoop = 0; // reset the count 
     tempArray = []; // reset the chunk 
    } 
    tempArray.push(gon.map_points[i].speed); // add item into chunk 
    currentLoop++; // increase count 
} 

マップ点の配列は点の完全数(例えば、それは117かもしれない)ではないので、私は最後を取得することはできませんない限り、これは正常に動作します私のチャンク配列に17ポイントが追加されました。

合計項目に関係なく、配列を25ポイントにまとめる方法はありますか?

+0

のようなチャンクを設定するために、スプライスを使用することができますループスルーします。あなたは回避策を行うことができますそのように –

+0

アレイを別のアレイにコピーするためにスライスを使用 –

+0

[分割アレイをチャンクに分割]の可能性があります(http://stackoverflow.com/questions/8495687/split-array-into-chunks) –

答えて

1

あなたは25でmap_pointsをdevideことができますし、何回も正確になります。この

var s = []; 
 
var result = []; 
 
function generate(){ 
 
for(var i=0 ; i< 117; i++){ 
 
    s.push(i); 
 
} 
 
} 
 
generate(); 
 
//console.log(s) 
 

 
while(s.length > 25){ 
 
    //console.log(s.splice(0,25)) 
 
    result[result.length] = s.splice(0,25); 
 
} 
 

 
result[result.length] = s; 
 

 
console.log(result);

1

あなたはArray#sliceとインデックスを使用してサイズでカウントアップすることができます。

var array = Array.apply(null, { length: 65 }).map(function (_, j) { return j; }), 
 
    chunks = [], 
 
    chunkSize = 25, 
 
    i = 0; 
 

 
while (i < array.length) { 
 
    chunks.push(array.slice(i, i + chunkSize)); 
 
    i += chunkSize; 
 
} 
 

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

関連する問題