在javascript中将多个数组拆分为相等的块

9nvpjoqh  于 2023-03-06  发布在  Java
关注(0)|答案(4)|浏览(181)

我有一个像这样的东西。

const obj = {
  r: [1,2,3,4,5,6,7],
  p: [8,9,10,11,12,13,14],
  e: [15,16,17,18,19,20,21,22,23,24]
}

如果要将其格式化为对象数组,则每个对象的组合值不应超过10个。例如,上面的对象应如下格式化。

const res = [
 {
   r: [1,2,3,4,5,6,7],
   p:[8,9,10],
 },
 {
   p:[11,12,13,14],
   e:[15,16,17,18,19,20]
 },
 {
   e: [21,22,23,24]
 }
]

如何实现这一点。帮助是感激的。

const splitArray = (obj, size) => {
 //based on size, I want to split that 
}
ql3eal8s

ql3eal8s1#

获取条目循环和拼接,直到没有更多的数据可用。

const
    data = { r: [1, 2, 3, 4, 5, 6, 7], p: [8, 9, 10, 11, 12, 13, 14], e: [15, 16, 17, 18, 19, 20, 21, 22, 23, 24] },
    entries = Object.entries(data),
    result = [],
    length = 10;

do {
    const r = {};
    let l = length,
        i = 0;
    
    while (l && entries[i]) {
        const part = entries[i][1].splice(i, l);
        r[entries[i][0]] = part;
        l -= part.length;
        if (entries[i][1].length) i++;
        else entries.splice(i, 1);        
    }
    
    result.push(r);
} while (entries.length)

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

lrpiutwd2#

不知道这是否有点愚蠢,但也许你可以尝试如下所示的方法:将所有内容放入一个数组中,并附上键,然后拆分成块,然后重新分组:

const obj = {
  r: [1,2,3,4,5,6,7],
  p: [8,9,10,11,12,13,14],
  e: [15,16,17,18,19,20,21,22,23,24]
};

const chunk_length = 10;

const result = Object.entries(obj)
  // create one array of key value pairs like: [['r', 1], ['r', 2] ... ['e', 23], ['e', 24]]
  .flatMap( ([key, values]) => values.map((v) => [key, v]) )
  // split this array into chunks of length chunk_length
  .reduce((acc, val, i) => {
    const chunk_index = Math.floor(i / chunk_length);
    
    acc[chunk_index] ??= [];
    acc[chunk_index].push(val);

    return acc;
  }, [])
  // convert each chunk into an object with values grouped by the original keys
  .map((chunk) =>
    chunk.reduce((acc, [key, n]) => {
      acc[key] ??= [];
      acc[key].push(n);
      return acc;
    }, {})
  );

console.log(result);
tsm1rwdh

tsm1rwdh3#

const obj = {
  r: [1, 2, 3, 4, 5, 6, 7],
  p: [8, 9, 10, 11, 12, 13, 14],
  e: [15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
}

const results = [{}]
let currentLineLength = 0;

Object.entries(obj).forEach(([key, values]) => {

    while (values.length > 0) {
      const nValuesToUse = Math.min(values.length, 10 - currentLineLength);
      results[results.length - 1][key] = values.slice(0, nValuesToUse);
      values = values.slice(nValuesToUse)
      currentLineLength += nValuesToUse;
      if (currentLineLength === 10) {
        results.push({});
        currentLineLength = 0
      }
    
    }

  })

console.log(JSON.stringify(results,null,2))
ocebsuys

ocebsuys4#

使用一个生成器函数给予你一个键,值对的流。
然后使用reduce将这些对推到一个对象中,每10个项目创建一个新对象,以便将它们分块。

const obj = {"r":[1,2,3,4,5,6,7],"p":[8,9,10,11,12,13,14],"e":[15,16,17,18,19,20,21,22,23,24]}

function* pick(o) {
  for(const [k,v] of Object.entries(o))
    for(const i of v) yield [k,i]
}

const splitArray = (obj, size) => [...pick(obj)].reduce((a,[k,v],i)=>
  (i%size ? (a[a.length-1][k]??=[]).push(v) : a.push({[k]:[v]}), a),[])

console.log(splitArray(obj, 10))

相关问题