按顺序将 ARRAY 拆分为块

Split ARRAY into chunks as they appear in sequence

我得到了一个对象数组,我需要按照它们在原始数组中的顺序将其分成三个块。例如

let arr = [{1},{2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}];

这个数组需要这样拆分:

let newArray = {a:[{1},{4},{7},{10},...}], b:[{2},{5},{8}], c:[{3},{6},{9}]};

{1} 不是有效的 js 结构

假设 arr 是一个对象数组,您可以:

  • 使用 String.fromCharCode(current + 97)
  • 生成滚动字符索引
  • 使用一个对象来拥有字符索引

let arr = [{name:1},{name:2}, {name:3}, {name:4}, {name:5}, {name:6}, {name:7}, {name:8}, {name:9}, {name:10}];

function transform(theArray, chunkValue) {
  let finalObject = {};
  let current = 0;
  let currentIndex;
  
  theArray.forEach(element => {
    currentIndex = String.fromCharCode(current + 97);
    if (!finalObject[currentIndex]) {
      finalObject[currentIndex] = [];
    }
    finalObject[currentIndex].push(element);
    current++;
    if (current === chunkValue) {
      current = 0;
    }
  });
  
  console.log(finalObject);
  return finalObject;
}

transform(arr, 3);

也许这种方法会有用

const data = [{1:1}, {2:2}, {3:3}, {4:4}, {5:5}, {6:6}, {7:7}, {8:8}, {9:9}, {10:10}];

const chunk = (arr, n) => arr.length ? [arr.slice(0, n), ...chunk(arr.slice(n), n)] : [];

const chunks = chunk(data, 3);
const rotated = chunks[0].map((_, colIndex) => chunks.map(row => row[colIndex]));
const result = rotated.map((arr, index) => 
  ({ [index]: arr.filter(Boolean) }));

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

reduce 可以根据索引

将每个值分配到其插槽上

因为您需要 a,b,c 而不是 0,1,2 ,所以这里需要一个小映射 mapNumLetter

let arr = ["{1}","{2}", "{3}", "{4}", "{5}", "{6}", "{7}", "{8}", "{9}", "{10}"];



// let newArray = {a:[{1},{4},{7},{10},...}], b:[{2},{5},{8}], c:[{3},{6},{9}]};

const mapNumLetter = {
  0:"a",
  1:"b",
  2:"c"
}

const newArray = arr.reduce((acc,cur,i) => {
  acc[mapNumLetter[i%3]].push(cur);
  return acc
},{a:[],b:[],c:[]})

console.log(newArray)

( 因为 {1} , {2} ... 不是有效对象,我将它们更改为文字 "{1}" , "{2}" ... )