簡體   English   中英

將項目數組拆分為 N 個數組

[英]Split Array of items into N Arrays

我想數字Array分成N個組,其中必須從責令更小的組。

例如,在下面的代碼中,將一個12 個數字的 Array 拆分為5個 Array,結果應該是平均拆分的,從大(組)到小:

source: [1,2,3,4,5,6,7,8,9,10,11,12]
  ⬇      
output: [1,2,3] [4,5,6] [7,8] [9,10] [11,12]

游樂場

 // set up known variables var arr = [1,2,3,4,5,6,7,8,9,10,11,12], numberOfGroups = 5, groups = []; // split array into groups of arrays for(i=0; i<arr.length; i++) { var groupIdx = Math.floor( i/(arr.length/numberOfGroups) ); // if group array isn't defined, create it if( !groups[groupIdx] ) groups[groupIdx] = []; // add arr value to group groups[groupIdx].push( arr[i] ) } // Print result console.log( "data: ", arr ); console.log( "groups: ", groups )


更新:

感謝 SimpleJ 的回答,我可以完成我的工作。
其用例是一種將 HTML 列表拆分為“分塊”列表的算法,這是使用CSS Columns無法輕松實現的想法。

演示頁面

我不是 100% 確定這應該如何在具有不同組數的不同大小的數組上工作,但這適用於您的 12 位示例:

 function chunkArray(arr, chunkCount) { const chunks = []; while(arr.length) { const chunkSize = Math.ceil(arr.length / chunkCount--); const chunk = arr.slice(0, chunkSize); chunks.push(chunk); arr = arr.slice(chunkSize); } return chunks; } var arr = [1,2,3,4,5,6,7,8,9,10,11,12]; console.log( chunkArray(arr, 5) )

我認為這更像是一個數學問題而不是 Javascript。

const getGroups = (arr, noOfGroups) => {
  const division = Math.floor(arr.length / numberOfGroups);
  const groups = [[]];
  let remainder = arr.length % numberOfGroups;
  let arrIndex = 0;
  for (let i = 0; i < noOfGroups; i++) {
    for (let j = division + (!!remainder * 1); j >= 0; j--) {
      groups[i].push(arr[arrIndex]);
      arrIndex += 1;
    }
    remainder -= 1;
  }

  return groups;
};

const myGroups = getGroups([1,2,3,4,5,6,7,8,9,10,11,12], 5);

myGroups 將是 [[1, 2, 3], [4, 5, 6], [7, 8], [9, 10], [11, 12]]

這適用於任意數量的組和玩家

@SimpleJ 答案的較短版本,並且不使用切片兩次。

 function splitArrayEvenly(array, n) { array = array.slice(); let result = []; while (array.length) { result.push(array.splice(0, Math.ceil(array.length / n--))); } return result; } console.log(splitArrayEvenly([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 5))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM