The whole idea is to separate one array into multiple chunks.
Given I have an array named "mainlist":
const mainlist = [
{ label: '1' },
{ label: '2' },
{ label: '3' },
{ label: '4' },
{ label: '5' },
{ label: '6' },
{ label: '7' },
{ label: '8' },
{ label: '9' },
]
I have a second array as a reference to produce final chunks of arrays.
const fixedlist = [
{ label: 'f1', position: 3 },
{ label: 'f1', position: 5 },
]
I simply want to separate items from a mainlist
based on each item’s position from fixedItems
list.
const output = {
list1: [
{ label: '1' },
{ label: '2' },
],
list2: [
{ label: '3' },
{ label: '4' },
],
list3: [
{ label: '5' },
{ label: '6' },
{ label: '7' },
{ label: '8' },
{ label: '9' },
],
}
There are different scenarios to take into consideration, given there are only 2 loops:
- for the first loop it should start slicing the array from the beginning till
position - 1
. in our case it’s2
. It should automatically create a new array withfields.slice(0, 2)
- it also checks if if previous item exists, and if so, if there is a gap between previous item position and the current one. In first occurence there is not, but on the second one there is position
5 - position 3 = 2
, which means it should create a new list with 2 elements starting from the last one until the current one. - if current loop is the last one, and there are still items left after it’s position, it should add them to new array list
2
Answers
After some reasoning I think you want to add those "fixed" markers into the list by their
position
which will split it to sublists. The trick is to first place the markers, then pour in all the rest. Lists of length 0 are ignored.