typescript 拆分数组的数组中特定数量的对象[重复]

rjee0c15  于 2023-03-19  发布在  TypeScript
关注(0)|答案(1)|浏览(109)

此问题在此处已有答案

(73个答案)
5天前关闭。
给出了以下数组:

[
  {
    "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
]

我想写一个函数,它以一个数字作为参数。基于这个数字,例如10,我想把十个对象合并成一个数组的数组。
如果数组中有22个对象,那么我需要有三个数组.
输入:[ { }, { }, { }, { }, { }, { }, { }, { }, ]
输出(两组):[ [ { }, { } ], [ { }, { } ], [ { }, { } ], [ { }, { } ] ]
我的方法类似于但我不知道如何检查我有多少对象,然后将它们合并到一个新的数组中。

// array = example above
// countOption = 10

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

我们的想法是用它来分页。

fumotvh3

fumotvh31#

使用Math.ceil(array.length/countOption)得到数组的个数,然后将原始数组的切片加到结果中

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)

相关问题