【发布时间】:2018-11-09 00:41:21
【问题描述】:
我正在尝试将子数组拆分为 3 个内部数组的块。
例如:
[{
title: "asd",
description: "asd"
}, {
title: "asz",
description: "sd"
}, {
title: "ws",
description: "sd"
}, {
title: "re",
description: "sd"
}, {
title: "32",
description: "xxs"
}, {
title: "xxc",
description: "11"
}]
我想将上子数组转换为如下所示的块
[
[{
title: "asd",
description: "asd"
}, {
title: "asz",
description: "sd"
}, {
title: "ws",
description: "sd"
}],
[{
title: "re",
description: "sd"
}, {
title: "32",
description: "xxs"
}, {
title: "xxc",
description: "11"
}]
]
我尝试了一些这样的示例,但它适用于这个数组['a','b','c','d','e'] 很好。下面是我试过的代码,
perChunk = 2 // items per chunk
inputArray = ['a', 'b', 'c', 'd', 'e']
inputArray.reduce((resultArray, item, index) => {
const chunkIndex = Math.floor(index / perChunk)
if (!resultArray[chunkIndex]) {
resultArray[chunkIndex] = [] // start a new chunk
}
resultArray[chunkIndex].push(item)
console.log(resultArray)
return resultArray
}, [])
但是,对于我的输入,它不起作用。
请建议我如何实现这一目标
【问题讨论】:
-
您的
perChunk是2,但该示例显然每个都有3对象...?此外,这可能会有所帮助:stackoverflow.com/a/44069560/519413 -
您尝试的代码对我有用,只是因为您的
perChunk = 2,它分成了每个包含 2 个项目而不是包含 3 个项目的块。 -
在处理
leftover elements时,您的expected output是什么?即array.length = 10但chunk size = 8因此leftover elements = 2 -
我在我的答案中添加了一个更新,使用过滤器从数组中删除空对象
标签: javascript jquery arrays angularjs