Last active
December 7, 2017 03:48
-
-
Save zoffyzhang/213a3e2f4bdb963e19210b1377f73273 to your computer and use it in GitHub Desktop.
reverseFlatten
This file contains 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
// I wrote this file in order to reverse the result from https://gist.github.com/aherve/3c958b02c8262e64e0873f05377129f1 | |
const expand = (array, eachGroupSize) => { | |
return array.reduce((acc, item, index) => { | |
index % eachGroupSize === 0 ? acc.push([]) : null | |
acc[acc.length - 1].push(item) | |
return acc | |
}, []) | |
} | |
const expandWithFill = (array, eachGroupSize, fillitem) => { | |
return array.reduce((acc, item, index) => { | |
index % eachGroupSize === 0 ? acc.push(new Array(eachGroupSize).fill(fillitem)) : null | |
acc[acc.length - 1][index % eachGroupSize] = item | |
return acc | |
}, []) | |
} | |
// test | |
let a = [1, 2, 3, 4, 5] | |
console.log(JSON.stringify(expand(a, 4))) | |
// => [[1, 2, 3, 4], [5]] | |
console.log(JSON.stringify(expandWithFill(a, 4, null))) | |
// => [[1, 2, 3, 4], [5, null, null, null]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment