0

I have a json in the below format.

    [
    {"id": 1, 
    "name": "peter" },
    {"id": 2, 
    "name": "john" },
    {"id": 3, 
    "name": "justin" }
    .
    .
    {"id": 500, 
"name": "david" },
    ]

I am trying to create an array in batches of 10 in the below format

[
{
 {"id": 1, 
        "name": "peter" },
.
.
 {"id": 10, 
        "name": "nixon" },
},

{
 {"id": 11, 
        "name": "nancy" },
.
.
 {"id": 20, 
        "name": "underwood" },
}
.
.
]

I tried using reduce and tried for loop to loop through it, but was unsuccessful

indra257
  • 66
  • 3
  • 24
  • 50

1 Answers1

0

Here's a demo.

const str = "abcdefghigklmnopqrstuvwxyz";
let data = [];
for(let i = 0; i < 26; i++){
  data.push({id : i, name: str.charAt(i)});
}

let res = data.reduce((acc, d) => {
  let groupId = Math.floor(d.id / 10);
  acc[groupId] = acc[groupId] || {};
  acc[groupId][d.id] = d;
  return acc;
 }, {});
console.log(Object.values(res));

If you can ensure that id is the same sequence as their position in array, i think simply slice will better.

user8510613
  • 1,242
  • 9
  • 27