Skip to content

Instantly share code, notes, and snippets.

@doesdev
Last active August 27, 2019 13:53
Show Gist options
  • Save doesdev/861111e6ab00030cedf65f59287f9d8a to your computer and use it in GitHub Desktop.
Save doesdev/861111e6ab00030cedf65f59287f9d8a to your computer and use it in GitHub Desktop.
Split Array into Arrays of X length
let srcAry = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
let splitBy = 3
let split = []
srcAry.forEach((val, i) => {
let ary = i % splitBy ? split[split.length - 1] : (split[split.length] = [])
ary.push(val)
})
console.log(split)
@doesdev
Copy link
Author

doesdev commented Aug 27, 2019

const dividedArray = (srcAry = [], splitBy = 1) => {
  const split = []

  srcAry.forEach((val, i) => {
    const ary = i % splitBy ? split[split.length - 1] : (split[split.length] = [])
    ary.push(val)
  })

  return split
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment