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!

Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
user3468894
  • 65
  • 1
  • 5

4 Answers4

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; }
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
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);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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]);
  }, []);
}