1

I want transform my array to array of arrays by attribute "icon".

const array = [
  { icon: true }, 
  { icon: false },
  { icon: false }, 
  { icon: true }, 
  { icon: false }
]

I need:

[[{icon: true}, {icon: false}, {icon: false}], [{{icon: true}, {icon: false}}]]

Attribute icon === true is a sign of the beginning of the formation of a new array.

I think you should use the function reduce.

array.reduce((result, item, index) => { ... }, [])

How best to write a transformation? Thanks!

1
  • 3
    please add what you have tried. Commented Jan 10, 2019 at 12:20

4 Answers 4

4

You can use .reduce() method as follow:

const data = [{ icon: true }, { icon: false }, { icon: false }, { icon: true }, { icon: false }]

const result = data.reduce((r, c) => {
  if(c.icon === true)
    r.push([c]);
  else
    r[Math.max(r.length - 1, 0)].push(c);
    
  return r;
},[]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

1 Comment

Thanks! It is perfectly!
0

You could use a while loop.

const array = [{ icon: true }, { icon: false }, { icon: false }, { icon: true }, { icon: false }]
i = 0;
result = [];
aux = [];
while(i <  array.length){
   if(array[i].icon){
     if(aux.length !== 0){
        result.push(aux);
        aux = [array[i]];
     }
     else
        aux.push(array[i]);
   }
   else
     aux.push(array[i]);
   i++;
}
result.push(aux);
console.log(result);

Comments

0

You could use a closure over the array for inserting. This prevents to look up the last item in the array.

const
    data = [{ icon: true }, { icon: false }, { icon: false }, { icon: true }, { icon: false }],
    result = data.reduce((a => (r, o) => {
        if (o.icon) r.push(a = []);
        a.push(o);
        return r;
    })(), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

const array = [
  { icon: true },
  { icon: false },
  { icon: false },
  { icon: true },
  { icon: false }
];

console.log(grouper(array));

function grouper(array) {
  return array.reduce((acc, next) => {
    const entry = [next];

    if (next.icon) return acc.concat([entry]);
    const beforeNextCollection = acc.slice(0, acc.length - 1);

    const nextCollection = acc[acc.length - 1];
    const updatedCollection = nextCollection.concat(entry);

    return beforeNextCollection.concat([updatedCollection]);
  }, []);
}

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.