将数组拆分为不同大小的块(4、3、3、3、4、3、3、3等) [英] Split array into different size chunks (4, 3, 3, 3, 4, 3, 3, 3, etc)

查看:63
本文介绍了将数组拆分为不同大小的块(4、3、3、3、4、3、3、3等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组: [1、2、3、4、5、6、7、9、10] .我需要将其分成不同大小的块,并使用以下简单模式:4,3,3,3,4,3,3,3,像这样:

I have an array like so: [1, 2, 3, 4, 5, 6, 7, 9, 10]. I need to chunk it into different size chunks, yet with a simple pattern of: 4, 3, 3, 3, 4, 3, 3, 3 like so:

[
    [ // four
        1,
        2,
        3,
        4
    ],
    [ // three (1/3)
        5,
        6,
        7
    ],
    [ // three (2/3)
        8,
        9,
        10
    ],
    [ // three (3/3)
        11,
        12,
        13
    ],
    [ // four
        14,
        15,
        16,
        17
    ],
    [ // three (1/3)
        18,
        19,
        20
    ], // and so on..
]

我尝试使用自定义的这段代码:

I have tried with this code I have customized:

const arr; // my array of values
const chuncked = arr.reduce((acc, product, i) => {
    if (i % 3) {
        return acc;
    } else if (!didFourWayReduce) {
        didFourWayReduce = true;
        fourWayReduces++;

        if ((fourWayReduces - 1) % 2) { // only make every second a "4 row"
            return [...acc, arr.slice(i, i + 3)];
        } else {
            return [...acc, arr.slice(i, i + 4)];
        }
    } else {
        didFourWayReduce = false;
        return [...acc, arr.slice(i, i + 3)];
    }
}, []);

几乎可以正常工作,它期望三分之三的第一个块(1/3)的块的最后一个元素为4.因此,每三个三的第一个块都重复一个键.像这样:

And it works, almost, expect that the first chunk of threes (1/3) have the last element of the chunk with 4. So 1 key is repeated every first chunk of three. Like so:

[
    [
        1,
        2,
        3,
        4
    ],
    [
        4, // this one is repeated, and it shouldn't be
        5,
        6
    ]
]

推荐答案

您可以采用两个索引,一个用于数据数组,另一个用于大小.然后以给定的长度对数组进行切片,然后将块推送到块数组.

You could take two indices, one for the data array and one for sizes. Then slice the array with a given length and push the chunk to the chunks array.

继续直到数据结束.

var data = Array.from({ length: 26 }, (_, i) => i + 1),
    sizes = [4, 3, 3, 3],
    i = 0,
    j = 0,
    chunks = [];

while (i < data.length) chunks.push(data.slice(i, i += sizes[j++ % sizes.length]));

console.log(chunks);

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

这篇关于将数组拆分为不同大小的块(4、3、3、3、4、3、3、3等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆