1

Lets say I have an array like this :

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}] 
 }
]

I need to check where combineNext is true and concat the next array item (if exists) to it to create a new array of arrays like this:

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}] 
  }
 ]
] 

What is the best way to have this output ?

2
  • Why is the first object in the result array? Commented Feb 20, 2018 at 18:08
  • I will map on the array of arrays after that so i will have 3 lists Commented Feb 20, 2018 at 18:10

1 Answer 1

4

You can do this with reduce method and check previous element. If the previous element has combineNext true you add current element to last element in accumulator otherwise you push new array.

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.