Skip to content

Chunk 函数

function chunk(array, size = 1)

传入一个一维数组,返回一个二维数组,将数组 array 拆分为多个 size 长度的数组。

参数

  1. array 需要处理的数组
  2. size 拆分的大小

例子

javascript
chunk(['a', 'b', 'c', 'd'], 2) // -> [['a', 'b'], ['c', 'd']]
// 剩余的元素不够 size,也组成一个区块
chunk(['a', 'b', 'c', 'd'], 3) // -> [['a', 'b', 'c'], ['d']]

Code

javascript
function chunk(array, size = 1) {
  if (array.length < 1) {
    return [];
  }
  const result = [];
  const max = size >= 1 ? size : 1;
  let slow = 0,
    fast = max;
  while (fast <= array.length) {
    if (fast !== 0 && fast % max === 0) {
      result.push(array.slice(slow, fast));
      slow = fast;
    }
    fast++;
  }
  if (slow < array.length) {
    result.push(array.slice(slow));
  }
  return result;
}

Test Cases

javascript
const { chunk } = require('../docs/algo/array/chunk');
describe('chunk', () => {
  it('case1', () => {
    expect(chunk(['a', 'b', 'c', 'd'], 2)).toEqual([
      ['a', 'b'],
      ['c', 'd'],
    ]);
  });
  it('case2', () => {
    expect(chunk(['a', 'b', 'c', 'd'], 3)).toEqual([['a', 'b', 'c'], ['d']]);
  });
  it('case3', () => {
    expect(chunk(['a', 'b', 'c', 'd'], 1)).toEqual([
      ['a'],
      ['b'],
      ['c'],
      ['d'],
    ]);
  });
  it('case4', () => {
    expect(chunk([], 1)).toEqual([]);
  });
  it('case5', () => {
    expect(chunk(['a', 'b'], 4)).toEqual([['a', 'b']]);
  });
});