简体   繁体   中英

Creating array of arrays of objects from array of objects

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?

If you are open to integrating other packages into the project, I believe the function chunk from Lodash serves exactly this purpose: https://lodash.com/docs/4.17.15#chunk

The code becomes as simple as (and much clear in terms of what is happening):

const chunks = _.chunk(chartdata, 20);

In general, since it seems you will be working a lot with arrays, consider integrating Lodash into your project, the library targets exactly the many operations one would want to perform with arrays. I have been working several years with the library in my projects, and hardly ever (if ever) came across an operation that was not covered by their functions.

There are some suggestions regarding optimization, but to be honest I never found importing the whole library to be a problem when it comes to bundle size.

let i,j, newArray = [],chunk = 20;
for (i=0,j=chartdata.length; i<j; i+=chunk) {
    newArray.push(chartdata.slice(i,i+chunk));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM