Skip to content

Instantly share code, notes, and snippets.

@alvaropinot
Created June 7, 2017 08:32
Show Gist options
  • Save alvaropinot/7dfe67aa306e340c49f4cf6819c8b95d to your computer and use it in GitHub Desktop.
Save alvaropinot/7dfe67aa306e340c49f4cf6819c8b95d to your computer and use it in GitHub Desktop.
group two elements each `n` elements with a nice offset :)
const transformIndex = (index, groupEach, offset) =>
offset + (index - offset - Math.ceil((index - offset) / groupEach))
const transformIndexEachThreeWithOneOffset = (index) => transformIndex(index, 3, 1)
function groupArrayEach(arr, groupEach=3, offset=0) {
return arr.reduce(function(acc, e, index) {
const newIndex = transformIndex(index, groupEach, offset)
acc[newIndex] = acc[newIndex] || []
acc[newIndex].push(e)
return acc
}, [])
}
console.log(group(Array(18).fill('').map((e, i)=>i)))
Array(20).fill('').map((e, i)=>i).map(transformIndexEachThreeWithOneOffset)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment