将分组对象数组平均分成两个

时间:2018-10-27 13:48:13

标签: javascript arrays split

所以可以说我有一个看起来像这样的数组:

var addresses = [[{house: "231 Main", id: "someID"},
                  {house: "233 Main", id: "someID"}],
                 [{house: "440 10th Street", id: "someID"},
                  {house: "443 10th Street", id: "someID"},
                  {house: "450 10th Street", id: "someID"}],
                 [{house: "440 11th Street", id: "someID"}]]

如何基于嵌套数组中的计数将2d数组拆分为两个稍微平衡的数组?因此,从拥有一个包含三个子数组(总共六个项)的数组到两个拥有每个子数组(总共三个项)的两个数组。

1 个答案:

答案 0 :(得分:2)

使用[].concat展平子数组,并使用slice将其拆分为两个子数组

const addresses = [[{house: "231 Main", id: "someID"},
                  {house: "233 Main", id: "someID"}],
                 [{house: "440 10th Street", id: "someID"},
                  {house: "443 10th Street", id: "someID"},
                  {house: "450 10th Street", id: "someID"}],
                 [{house: "440 11th Street", id: "someID"}]]

const flattened = [].concat(...addresses)
const length = flattened.length

const result = [
  flattened.slice(0, Math.floor(length/2)),
  flattened.slice(Math.floor(length/2))
]

console.log(result)