Currently my data is an array with a long list of objects in the format:
[
{ name: 'example' },
{ name: 'example' },
...
]
What I am trying to do is to convert this list into arrays of arrays of objects at a given interval, 20.
I want this format:
[
[
{ name: 'example' },
{ name: 'example' },
...18 more rows
],
[
{ name: 'example' },
{ name: 'example' },
...18 more rows
],
]
chartdata contains the data in initial format, I am trying to get the new format in 'newArray'. In order to achieve this I have put:
let newArray = [];
let data = [];
chartdata.forEach((x, i) => {
if(i === chartdata.length - 1 ){
newArray.push(data)
data = []
}
if(i%20===0){
newArray.push(data)
data = []
}
data.push(x);
})
console.log('newArray',newArray)
There are two things I do not understand.
The console log shows the below:
Why is there an empty array in the first index of newArray?
- Thank you, I have added && i !== 0 in the second if statement.
Why does index 4 of newArray only have 19 values?
The first question is fairly easy to resolve, however the second question I do not understand how to fix. Please can anyone provide some help?

0%20 = 0so the 2nd condition gets true and the empty array is pushed into the final array