I’ve got an array of objects that each carry a columnSpan
property with a numeric value between 1 and 16.
[
{
"columnSpan": 4,
"id": "DatoCmsEntry-MaixsOYtSwS7mloD59Rvng"
},
{
"columnSpan": 4,
"id": "DatoCmsEntry-fEuNly9-QFiRh4DoUZ-Y_w"
},
{
"columnSpan": 2,
"id": "DatoCmsEntry-HsAgXDMHQkSXS_4lKSGfGA"
},
{
"columnSpan": 2,
"id": "DatoCmsEntry-BM-fSBruSM67IFzCrBSLBg"
},
{
"columnSpan": 3,
"id": "DatoCmsEntry-JPushhKGSBCwR_uWcwIFSw"
},
{
"columnSpan": 3,
"id": "DatoCmsEntry-Q0sfjP9ZQZSDZZVP_sI9ew"
},
{
"columnSpan": 2,
"id": "DatoCmsEntry-CdVhbQENQ4ib2z4w3wc20Q"
},
{
"columnSpan": 2,
"id": "DatoCmsEntry-Fn2U_0CuQDiBEOZLmS3ovQ"
}
]
I need to split this array up into a multidimensional array where each top-level item represents a collection of records where the total columnSpan
is 16 or less, keeping the original order, like this:
[
[
{
"columnSpan": 4,
"id": "DatoCmsEntry-MaixsOYtSwS7mloD59Rvng"
},
{
"columnSpan": 4,
"id": "DatoCmsEntry-fEuNly9-QFiRh4DoUZ-Y_w"
},
{
"columnSpan": 2,
"id": "DatoCmsEntry-HsAgXDMHQkSXS_4lKSGfGA"
},
{
"columnSpan": 2,
"id": "DatoCmsEntry-BM-fSBruSM67IFzCrBSLBg"
},
{
"columnSpan": 3,
"id": "DatoCmsEntry-JPushhKGSBCwR_uWcwIFSw"
}
],
[
{
"columnSpan": 3,
"id": "DatoCmsEntry-Q0sfjP9ZQZSDZZVP_sI9ew"
},
{
"columnSpan": 2,
"id": "DatoCmsEntry-CdVhbQENQ4ib2z4w3wc20Q"
},
{
"columnSpan": 2,
"id": "DatoCmsEntry-Fn2U_0CuQDiBEOZLmS3ovQ"
}
]
]
Suggestions on ways to pull this off?
3
Answers
you can pull this off by keeping 2 extra variables to track the current chunk and the current total. Anyway you need an array to store the chunks. Then it is just a loop. I keep adding to the current chunk until it is less than or equal to 16, else I’m resetting the current chunked and total variables. Also I directly do
currentChunk = [item]
currentTotal = item.columnSpan
instead ofcurrentChunk = []
¤tChunk.push(item)
andcurrentTotal = 0
¤tTotal += item.columnSpan
The final if check is needed to add the final chunk
or same thing using a reduce
I will suggest an option with the use of reduce. The script goes sequentially through the array and counts ColumnSpan. If no more than 16, it adds to the current array, if it exceeds, it adds to the next one, and so on.
OR
Reduce the array. In the reducer start by checking if a new chunk should be added. Always add the current item to the last chunk.