0

I build a function to put array into chunk arrays like:

function conditionalChunk(array, size, rules = {}) {
  let copy = [...array],
      output = [],
      i = 0;

  while (copy.length)
    output.push( copy.splice(0, rules[i++] ?? size) )

  return output
}

const input = [[1,2,3],[4,5,6,7]],
            output = conditionalChunk(input.flat(), 3, { 0: 2, 1: 2 });
      

// OUTPUT: [[1,2],[3,4],[5,6,7]]

and the chunk is actually pages in my case but I need some more details to put there so now I have:

[{'page_layout': 1, 'theme': 0, 'items', [1,2,3]}, {'page_layout': 5, 'theme': 1, 'items', [4,5,6,7]}]

How can I isolate items to build chunk arrays like in the case above without objects...

I was tried: output = conditionalChunk(input.flat().items, 3, { 0: 2, 1: 2 }); but that is not the solution and I got error" Uncaught TypeError: array is not iterable

4
  • 1
    input.flat().items -> input.flaMapt(x => x.items) Commented Jul 4, 2021 at 10:16
  • ok, but then I lose the object data like 'page_layout' Commented Jul 4, 2021 at 10:19
  • Then what do you want to do here? The code you tried hinted at trying to extract the items as a flat array. If you don't want to do that, there is probably no reason to flatten anything. You'd need to explain what the goal is. What do you want to go over and how? What is the expected output? Commented Jul 4, 2021 at 10:52
  • expected output need to be like [{'page_layout': 1, 'items': [1,2]}, {'page_layout': 2, 'items': [3,4]}, [{'page_layout': some_variable, 'items': [5,6,7]}]] so I need to move item array elements from an object to other Commented Jul 4, 2021 at 10:58

1 Answer 1

1

You can extract all the items out first and then flatten them, like this -

const flattenedInputs = input.map(({ items }) => items).flat()
output = conditionalChunk(flattenedInputs, 3, { 0: 2, 1: 2 });
Sign up to request clarification or add additional context in comments.

5 Comments

that's ok, I got [[1,2],[3,4],[5,6]] but I lose the object data because I need to get array-like: [{'page_layout': 1, 'items': [1,2]}, {'page_layout': 2, 'items': [3,4]}, [{'page_layout': some_variable, 'items': [5,6,7]}];];
Okay, and how will you decide the page_layout of each chunk(page)? if you have a predefined way to do that, then you can add these information while pushing to output output.push({ items: copy.splice(0, rules[i++] ?? size) , page_layout: getPageLayout })
page_layout stay the same as it is... for new chunk its etc. 8
Okay, and what if a chunk is made up of items from two different objects with different pag_layouts?
page_layout stay the same but if new chunk need to be created then page_layout will be: 8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.