【问题标题】:How can I split an array into chunks but have it fill each array by going one by one如何将数组拆分为块,但让它一个接一个地填充每个数组
【发布时间】:2018-12-11 02:00:06
【问题描述】:

我正在使用这个函数来创建一个数组块:

function chunkArray(myArray, chunk_size) {
    let results = [];
    while (myArray.length) {
        results.push(myArray.splice(0, chunk_size));
    }
    return results;
}

但是,如果我们假设原始数组是 [1, 2, 3, 4, 5, 6] 并且我将它分成 3 个部分,我将得到以下结果:

[
    [1, 2],
    [3, 4],
    [5, 6]
]

但是,我希望它分块成在三者之间跳跃的数组,例如:

[
    [1, 4],
    [2, 5],
    [3, 6]
]

最好的方法是什么?

【问题讨论】:

  • "块成在两者之间跳跃的数组" ?你能解释一下你的意思吗?乐于助人,但我很困惑。其他的?
  • @zfrisch 我在原始帖子中的措辞混乱,只是对其进行了编辑。现在通过示例可能更有意义。
  • const chunkArray = (myArray, chunk_size) => myArray.reduce((p, c, i) => (p[i % chunk_size].push(c), p), Array(chunk_size).fill().map(e => []));
  • chunk_size,还是chunk_count,因为虽然代码说的是前者,但问题确实描述的是后者。
  • 另外,这个函数的良好版本不应该改变输入数组。

标签: javascript arrays node.js


【解决方案1】:

您可以使用以下代码:

function chunkArray(myArray, chunk_size) {
    let results = new Array(chunk_size);
    for(let i = 0; i < chunk_size; i++) {
        results[i] = []
    }
    // append arrays rounding-robin into results arrays.
    myArray.forEach( (element, index) => { results[index % chunk_size].push(element) });
    return results;
}

const array = [1,2,3,4,5,6];
const result = chunkArray(array, 3)
console.log(result)

【讨论】:

    【解决方案2】:

    您可以将索引的剩余部分与所需的索引大小一起使用并推送该值。

    var array = [1, 2, 3, 4, 5, 6],
        size = 3,
        result = array.reduce((r, v, i) => {
            var j = i % size;
            r[j] = r[j] || [];
            r[j].push(v);
            return r;
        }, []);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 优雅简约。我喜欢它。
    【解决方案3】:

    我会这样做:

    function chunkArray(src, chunkSize ) {
      const chunks = Math.ceil( src.length / chunkSize );
      const chunked = [];
    
      for (let i = 0; i < src.length; ++i) {
        const c       = i % chunks;
        const x       = chunked[c] || (chunked[c]=[]);
        x[ x.length ] = src[i];
      }
    
      return chunked;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      • 2012-05-28
      相关资源
      最近更新 更多