shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.92k stars 510 forks source link

【Q643】如何实现 chunk 函数,数组进行分组 #661

Open shfshanyue opened 3 years ago

shfshanyue commented 3 years ago

示例如下:

// => [[1, 2, 3], [4, 5, 6], [7]]
chunk([1, 2, 3, 4, 5, 6, 7], 3)
shfshanyue commented 3 years ago
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
}
haotie1990 commented 3 years ago
function chunk(array, limit) {
  limit = array.length <= limit ? array.length : limit;
  const result = [];
  while(array.length) {
    result.push(array.splice(0, limit));
  }
  return result;
}
shfshanyue commented 3 years ago

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

kirazZ1 commented 1 year ago
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;
    }
  }, []);
}