所以可以说我有一个看起来像这样的数组:
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数组拆分为两个稍微平衡的数组?因此,从拥有一个包含三个子数组(总共六个项)的数组到两个拥有每个子数组(总共三个项)的两个数组。
答案 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)