Answer the question
In order to leave comments, you need to log in
How to split an array into equal parts?
I have an array of objects:
var array = [
{
"id": 1
},
{
"id": 2
},
{
"id": 3
},
{
"id": 4
}
]
var newArray = [
[
{
"id": 1
},
{
"id": 2
}
],
[
{
"id": 3
},
{
"id": 4
}
]
]
Answer the question
In order to leave comments, you need to log in
function chunkArray(array, chunk) {
const newArray = [];
for (let i = 0; i < array.length; i += chunk) {
newArray.push(array.slice(i, i + chunk));
}
return newArray;
}
const res = chunkArray(array, 2);
console.log(res);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question