JavaScript条件数组重构

时间:2018-02-20 18:04:54

标签: javascript ecmascript-6

假设我有一个这样的数组:

myArray = 
[
 {
  combineNext: false,
  title: 'Title1',
  items: [{item1},{item2}] 
 }, 
 {
  combineNext: true,
  title: 'Title2',
  items: [{item3}] 
 },
 {
  combineNext: true
  title: 'Title3',
  items: [{item4},{item5}] 
 },
 {
  combineNext: false
  title: 'Title4',
  items: [{item6}] 
 },
 {
  combineNext: true
  title: 'Title5',
  items: [{item7},{item8},{item9}] 
 }
]

我需要检查combineNext的真实位置,并将下一个数组项(如果存在)连接到它,以创建一个新的数组数组,如下所示:

theNewArrayofArrays = 
[
 [
  {
  combineNext: false,
  title: 'Title1',
  items: [{item1},{item2}] 
  }
 ], 
 [
  {
   combineNext: true,
   title: 'Title2',
   items: [{item3}] 
  },
  {
   combineNext: true
   title: 'Title3',
   items: [{item4},{item5}] 
  },
  {
   combineNext: false
   title: 'Title4',
   items: [{item6}] 
  },
 ],
 [
  {
   combineNext: true
   title: 'Title5',
   items: [{item7},{item8},{item9}] 
  }
 ]
] 

获得此输出的最佳方法是什么?

1 个答案:

答案 0 :(得分:4)

您可以使用reduce方法执行此操作并检查上一个元素。如果前一个元素为combineNext为真,则将当前元素添加到累加器中的最后一个元素,否则推送新数组。



const myArray = [{"combineNext":false,"title":"Title1"},{"combineNext":true,"title":"Title2"},{"combineNext":true,"title":"Title3"},{"combineNext":false,"title":"Title4"},{"combineNext":true,"title":"Title5"}]

const result = myArray.reduce((r, e, i, arr) => {
  const prev = arr[i - 1];
  if (prev && prev.combineNext) r[r.length - 1].push(e)
  else r.push([e])
  return r;
}, [])

console.log(result)