返回介绍

solution / 2600-2699 / 2677.Chunk Array / README_EN

发布于 2024-06-17 01:03:01 字数 2898 浏览 0 评论 0 收藏 0

2677. Chunk Array

中文文档

Description

Given an array arr and a chunk size size, return a chunked array. A chunked array contains the original elements in arr, but consists of subarrays each of length size. The length of the last subarray may be less than size if arr.length is not evenly divisible by size.

You may assume the array is the output of JSON.parse. In other words, it is valid JSON.

Please solve it without using lodash's _.chunk function.

 

Example 1:

Input: arr = [1,2,3,4,5], size = 1
Output: [[1],[2],[3],[4],[5]]
Explanation: The arr has been split into subarrays each with 1 element.

Example 2:

Input: arr = [1,9,6,3,2], size = 3
Output: [[1,9,6],[3,2]]
Explanation: The arr has been split into subarrays with 3 elements. However, only two elements are left for the 2nd subarray.

Example 3:

Input: arr = [8,5,3,2,6], size = 6
Output: [[8,5,3,2,6]]
Explanation: Size is greater than arr.length thus all elements are in the first subarray.

Example 4:

Input: arr = [], size = 1
Output: []
Explanation: There are no elements to be chunked so an empty array is returned.

 

Constraints:

  • arr is a valid JSON array
  • 2 <= JSON.stringify(arr).length <= 105
  • 1 <= size <= arr.length + 1

Solutions

Solution 1

function chunk(arr: any[], size: number): any[][] {
  const ans: any[][] = [];
  for (let i = 0, n = arr.length; i < n; i += size) {
    ans.push(arr.slice(i, i + size));
  }
  return ans;
}
/**
 * @param {Array} arr
 * @param {number} size
 * @return {Array[]}
 */
var chunk = function (arr, size) {
  const ans = [];
  for (let i = 0, n = arr.length; i < n; i += size) {
    ans.push(arr.slice(i, i + size));
  }
  return ans;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文