将数组拆分为给定大小的块,最小块大小 [英] Splitting an array up into chunks of a given size with a minimum chunk size

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

问题描述

有很多将数组拆分为块的示例,例如:将数组拆分为块,但我也想保持每个块的最小大小,最后一个块的大小不应小于预期的最小大小.

There are a lots of examples of splitting an array into chunks, like this one: Split array into chunks, but I also wanted to keep the minimum size of each chunk, last chunk's size shouldn't be smaller than the expected minimum size.

比方说,您有一个包含1001个项目的数组,并且想要拆分为100个块.最后一个块的大小为1,在某些情况下,这可能不是预期的结果.因此,您还具有期望的最小块大小.有什么可能的方法?

Let's say you have an array with 1001 items, and you want to split into chunks of 100. The last chunk will became size of 1, in certain cases it might not be the expected result. So you also have minimum size of the chunk expected. What are the possible approaches?

推荐答案

1.如果最后一个块中的元素少于最少元素,则将其删除:

const chunk = (arr, size, min) => {
  const chunks = arr.reduce(
    (chunks, el, i) =>
      (i % size ? chunks[chunks.length - 1].push(el) : chunks.push([el])) && chunks,
    []
  );
  const l = chunks.length;

  if (chunks[l - 1].length < min) chunks.pop();
  return chunks;
};

2.将最后一个块添加到上一个块:

const chunk = (arr, size, min) => {
  const chunks = arr.reduce(
    (chunks, el, i) =>
      (i % size ? chunks[chunks.length - 1].push(el) : chunks.push([el])) && chunks,
    []
  );
  const l = chunks.length;

  if (chunks[l - 1].length < min) chunks[l - 2].push(...chunks.pop());
  return chunks;
};

3.将最后一块平均分配到其他块中:

const chunk = (arr, size, min) => {
  const chunks = arr.reduce(
    (chunks, el, i) =>
      (i % size ? chunks[chunks.length - 1].push(el) : chunks.push([el])) && chunks,
    []
  );
  const l = chunks.length;

  if (chunks[l - 1].length < min) {
    const lastChunk = chunks.pop();
    let i = 0;

    while (lastChunk.length) {
      chunks[i % (l - 1)].push(lastChunk.pop());
      i += 1;
    }
  }

  return chunks;
};

希望这会有所帮助.

这篇关于将数组拆分为给定大小的块,最小块大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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