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

509次阅读  |  发布于9月以前

塞纳河,巴黎,法国

示例如下:

// => [[1, 2, 3], [4, 5, 6], [7]]
chunk([1, 2, 3, 4, 5, 6, 7], 3)
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
}

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8