Skip to content

Instantly share code, notes, and snippets.

@imbyc
Created May 26, 2020 02:46
Show Gist options
  • Save imbyc/31af4c0f30884bd2cef304cc2f14c5e2 to your computer and use it in GitHub Desktop.
Save imbyc/31af4c0f30884bd2cef304cc2f14c5e2 to your computer and use it in GitHub Desktop.
[js 将一维数组按指定长度转为二维数组] https://xugaoyi.com/pages/f1acb712033ac8da/
function pages(arr, len) {
const pages = []
arr.forEach((item, index) => {
const page = Math.floor(index / len)
if (!pages[page]) {
pages[page] = []
}
pages[page].push(item)
})
return pages
}
// 使用
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(pages(arr, 3)) // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
console.log(pages(arr, 8)) // [[1, 2, 3, 4, 5, 6, 7, 8], [9]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment