JavaScript如何按自定义规则实现对象数组的分块处理
JavaScript 自定义规则数组分块实现
原始数组结构
const arr = [ { item: { 0: 'asd' }, que: '1.question asdsad ... ' }, { item: { 0: 'asd' }, que: '2.question asdsad ... ' }, { item: { 0: 'asd', 1: 'asdsa', 2: 'asdsa', 3: 'asdsa' }, que: '3.question asdsad ... ' }, { item: { 0: 'xx', 1: 'ssss', 2: 'ggg' }, que: 'Question asdsad ... ' }, { item: { 0: 'asd' }, que: '4.question asdsad ... ' }, { item: { 0: 'asd' }, que: '5.sdd asdsad ... ' }, { item: { 0: 'bbb', 1: 'bbb' }, que: 'Dsad question asdsad ... ' } ]
分块规则
- 每个分块最大长度为2
- 保持原数组元素顺序不变
- 若元素
item属性的键数量≥3,该元素单独作为一个分块 - 若元素
que属性值不以数字开头,该元素单独作为一个分块
实现代码
你原本使用reduce的思路是可行的,只需要补充判断逻辑即可:
const result = arr.reduce((acc, curr) => { // 先判断当前元素是否需要单独成块 const isNeedSingle = Object.keys(curr.item).length >= 3 || isNaN(Number(curr.que[0])) if (isNeedSingle) { acc.push([curr]) return acc } // 不需要单独成块时,判断最后一个分块是否还能存入元素 const lastChunk = acc.at(-1) if (lastChunk && lastChunk.length < 2) { lastChunk.push(curr) } else { acc.push([curr]) } return acc }, [])
输出结果验证
console.log(result) /* 输出和你预期的结构完全一致: [ [ { item: { '0': 'asd' }, que: '1.question asdsad ... ' }, { item: { '0': 'asd' }, que: '2.question asdsad ... ' } ], [ { item: { '0': 'asd', '1': 'asdsa', '2': 'asdsa', '3': 'asdsa' }, que: '3.question asdsad ... ' } ], [ { item: { '0': 'xx', '1': 'ssss', '2': 'ggg' }, que: 'Question asdsad ... ' } ], [ { item: { '0': 'asd' }, que: '4.question asdsad ... ' }, { item: { '0': 'asd' }, que: '5.sdd asdsad ... ' } ], [ { item: { '0': 'bbb', '1': 'bbb' }, que: 'Dsad question asdsad ... ' } ] ] */
内容的提问来源于stack exchange,提问作者Kobayashi
相关产品推荐
相关产品推荐

