# How to convert the array?

How to convert array to type this
``````let array = [
{ name: 'Alex', year: 21 }, { name: 'Vasya', year: 14 } ....
]``````

in an array of this type
``````let array = [
[
{ name: 'Alex', year: 21 }, { name: 'Vasya', year: 14 }
],
[
......
]
]``````

in this case each sub-array must be 2 elements
March 23rd 20 at 19:24
3 answers
March 23rd 20 at 19:26
Solution
``array.reduce((acc, n, i) => ((acc[i / 2 | 0] = acc[i / 2 | 0] || []).push(n), acc), [])``

or

``[...Array(Math.ceil(array.length / 2))].map((n, i) => array.slice(i * 2, (i + 1) * 2))``
March 23rd 20 at 19:28
Solution
``````const array = [
{ name: 'Alex1', year: 13 },
{ name: 'Alex2', year: 14 },
{ name: 'Alex3', "year": 15 },
{ name: 'Alex4', "year": 16 },
{ name: 'Alex5', year: 17 }
];
const result = [];
let chunkSize = 2;

for (let i=0; i < array.length; i += chunkSize) {
const chunk = array.slice(i, i + chunkSize);
result.push(chunk);
}

console.log(result);``````
March 23rd 20 at 19:30
Solution
``````const result = array.reduce((acc, el, i) => {
if (i % 2 === 0) {
acc.push([]);
}
acc[acc.length - 1].push(el);
return acc;
}, []);``````

Find more questions by tags JavaScript