1

I have a list object like below

[{a:"0"},{a:"1"},....{a:"39"}]

I want to have a list like the one below.I need a result like the below.

{
  "list1":[{a:"0"},{a:"1"},{a:"2"},{a:"3"}],
  "list2":[{a:"4"},{a:"5"},{a:"6"},{a:"7"}],
  .
  .
  .
  "list10":[{a:"36"},{a:"37"},{a:"38"},{a:"39"}],
}

Thanks for help me.

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
Saeed As
  • 9
  • 3

6 Answers6

1

You can use below code:

const items = [{a: "0"}, {a: "1"}, {a: "2"}, {a: "3"}, {a: "4"}, {a: "5"}, {a: "6"}, {a: "7"}, {a:"8"}, {a:"9"}, {a:"10"}];
let newItems = {};
let i = 1;
while(items.length){
    newItems[`list${i}`] = items.splice(0,4);
    i++;
}
console.log(newItems)

If you want too kep the items immutable you can copy it into another array before while loop, like this const copyItems = [...items] and using copyItems in while.

Saeed Shamloo
  • 6,199
  • 1
  • 7
  • 18
0

You can use a reduce to achieve this

const items = [{ a: "0" }, { a: "1" }, { a: "2" }, { a: "3" }, { a: "4" }, { a: "5" }, { a: "6" }, { a: "7" }];
items.reduce((accum, curr, index) => {
  const key = `list${1 + Math.floor(index / 4)}`;
  accum[key] = accum[key] || [];
  accum[key].push(curr);
  return accum;
}, {});
Ayman El Temsahi
  • 2,600
  • 2
  • 17
  • 27
0

I believe this might be what you're looking for. This will split the big array into smaller ones and store each array with a size of 4 in the arrayOfArrays.

var bigarray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var size = 4; var arrayOfArrays = [];
for (var i=0; i<bigarray.length; i+=size) {
  arrayOfArrays.push(bigarray.slice(i,i+size));
}
console.log(arrayOfArrays); // [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]
Zoë
  • 1
0

You can do that using slice() data...

const arr = [{a:"0"},{a:"1"},{a:"2"},{a:"3"},{a:"4"},{a:"5"},{a:"6"},{a:"7"}];

const arr2 = [];

var i,j;
for (i = 0; i < arr.length; i = i + 4) {
    arr2.push(arr.slice(i, i + 4));
}
    
console.log(arr2);
Faheem azaz Bhanej
  • 2,328
  • 3
  • 14
  • 29
0
var data = [{a:"0"},{a:"1"},{a:"2"},{a:"3"}, {a:"4"},{a:"5"},{a:"6"},{a:"7"},{a:"8"},{a:"9"}]

const sliceData = (data, size) => {
    var result = [];
    for(var i = 0; i < data.length; i += size){
       result.push(data.slice(i, i + size));
   }
  return result;
}

console.log(sliceData(data, 4));

result

[
  [ { a: '0' }, { a: '1' }, { a: '2' }, { a: '3' } ],
  [ { a: '4' }, { a: '5' }, { a: '6' }, { a: '7' } ],
  [ { a: '8' }, { a: '9' } ]
]
Shashikamal R C
  • 512
  • 3
  • 8
0

Lodash, if you don't mind

Use _.chunk to split array into groups the length of size.

import _ from 'lodash';

data = [{a:"0"},{a:"1"},{a:"2"},{a:"3"}, {a:"4"},{a:"5"},{a:"6"},{a:"7"},{a:"8"},{a:"9"}];
const size = 4;
const result = _.chunk(data, size)
   .reduce((acc, item, index) => ({ ...acc, [`list${index + 1}`]: item }), {});

console.log(result);
//{list1: Array(4), list2: Array(4), list3: Array(2)}
A1exandr Belan
  • 4,442
  • 3
  • 26
  • 48