-2

The following array is given:

[
  {
    "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"
        ]
      }
    ]
  },
  .... possibly more objects but removed to keep example short
]

I want to write a function which is taking a number as parameter. Based on this number, for example 10, I want to merge ten objects into an Arrays of Array.

If I have 22 objects in my array, then I want to have three arrays in my array.

Input: [ { }, { }, { }, { }, { }, { }, { }, { }, ]

Output (group by two): [ [ { }, { } ], [ { }, { } ], [ { }, { } ], [ { }, { } ] ]

My approach would be something like but I do not figure out how to check how many objects I have and then merge them into a new array.

// array = example above
// countOption = 10

const splitArrayByCount = (array, countOption) => {
  return array.map(object => {
    if (array.length > countOption) {
      return [object]
    }
  })
};

The idea is to use this for pagination.

mrks
  • 5,439
  • 11
  • 52
  • 74
  • "If I have 22 objects in my array,", please make your input reflect your issue. There arn't 22 objects in that array? – 0stone0 Mar 14 '23 at 13:22
  • @0stone0 removed objects from array to keep example short. Array could be just two objects but also like 70. – mrks Mar 14 '23 at 13:23
  • The problem is unclear to me. Could you provide specific input and output that you're after, please? – mingos Mar 14 '23 at 13:24
  • Ah oke @mrks, maybe clarify that in your question. Seems like this is a valid duplcate for the linked question. – 0stone0 Mar 14 '23 at 13:25

1 Answers1

2

Use Math.ceil(array.length/countOption) to get number of arrays. Then add slice of original to result

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
const countOption= 10
let result = []

for (let i = 0; i < Math.ceil(array.length / countOption); i++) {
  result.push(array.slice(i * countOption, (i + 1) * countOption))
}
console.log(result)
depperm
  • 10,606
  • 4
  • 43
  • 67