Presented below is an array:
[
{
"id": "34285952",
"labs": [
{
"id": "13399-17",
"location": "Gambia",
"edge": ["5062-4058-8562-2942-2107-2064-58"]
}
]
},
{
"id": "85130775",
"labs": [
{
"id": "52504-72",
"location": "Nepal",
"edge": [
"5232-9427-8339-7218-3936-9389-52",
"6375-9293-7064-5043-6869-4773-65",
"8547-4739-6334-3896-7208-8243-67"
]
}
]
},
{
"id": "67817268",
"labs": [
{
"id": "17891-68",
"location": "U.S.",
"edge": [
"6383-7536-7257-4713-9494-9910-93",
"6743-8803-1251-1173-5133-2107-19"
]
}
]
},
.... other objects may exist but are omitted for brevity
]
Create a function that accepts a number as input. This function should then group the objects in the array based on this number, such as grouping ten objects into Arrays of Array.
If there are 22 objects in the array, the output should consist of three arrays within the main array.
For instance:
Input:
[ { }, { }, { }, { }, { }, { }, { }, { }, ]
Output (grouped by two):
[ [ { }, { } ], [ { }, { } ], [ { }, { } ], [ { }, { } ] ]
An initial approach could involve counting the objects and then merging them accordingly:
// array = see above example
// countOption = 10
const splitArrayByCount = (array, countOption) => {
return array.map(object => {
if (array.length > countOption) {
return [object]
}
})
};
This concept can be useful for pagination purposes.