高级前端
手写代码
【Q643】如何实现 chunk 函数,数组进行分组

如何实现 chunk 函数,数组进行分组

更多描述 示例如下:

// => [[1, 2, 3], [4, 5, 6], [7]]
chunk([1, 2, 3, 4, 5, 6, 7], 3);

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 661 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

function chunk(list, size) {
  const l = [];
  for (let i = 0; i < list.length; i++) {
    const index = Math.floor(i / size);
    l[index] ??= [];
    l[index].push(list[i]);
  }
  return l;
}

或者直接构造出每一个 chunk

function chunk(list, size) {
  const l = [];
 
  for (let i = 0; i < list.length; i += size) {
    const chunk = list.slice(i, i + size);
    l.push(chunk);
  }
 
  return l;
}

Author 回答者: haotie1990 (opens in a new tab)

function chunk(array, limit) {
  limit = array.length <= limit ? array.length : limit;
  const result = [];
  while (array.length) {
    result.push(array.splice(0, limit));
  }
  return result;
}

Author 回答者: shfshanyue (opens in a new tab)

@haotie1990 这种实现方式很漂亮,但是有可能有副作用,当传入数组时,数组会被置空,可以先 [...array] 浅拷贝一份

Author 回答者: kirazZ1 (opens in a new tab)

function chunk(list = [], size) {
  return list.reduce((pre, cur) => {
    const length = pre.length;
    if (length === 0 || pre[length - 1].length === size)
      return pre.concat([[cur]]);
    else {
      pre[length - 1].push(cur);
      return pre;
    }
  }, []);
}