Created
June 7, 2017 08:32
-
-
Save alvaropinot/7dfe67aa306e340c49f4cf6819c8b95d to your computer and use it in GitHub Desktop.
group two elements each `n` elements with a nice offset :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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