Zain
Zain

Reputation: 482

Divide array based on inner array conditions

I have an array like :

let colors=[ [ 31236780195925 ],[],[],[],[],[ 31236780163157 ],[],[],[ 31236780228693 ],[],[],[],[],[] ]

inner array values can differ, I want result like in the following structure

let Red=[[ 31236780195925 ],[],[],[],[]];
let Green=[[ 31236780163157 ],[],[]];
let Blue=[[ 31236780228693 ],[],[],[],[],[]];

Upvotes: 2

Views: 119

Answers (3)

Aksen P
Aksen P

Reputation: 4599

You can use the following solution. It checks length of each element and if it becomes more then 0 it starts to fill next index. Red has [0] index, Green has [1] index, Blue has [2] index of resultant array.

var colors=[ [31236780195925],[],[],[],[],[ 31236780163157 ],[],[],[ 31236780228693 ],[],[],[],[],[] ];

var res_ar = []; 
var i = -1;
 
colors.forEach(ar => {
      if (ar.length > 0) {
        i++;
        res_ar.push([]);
      }
        res_ar[i].push(ar); 
})

  // console.log(res_ar) 

console.log(res_ar[0]);
console.log(res_ar[1]);
console.log(res_ar[2]);

Upvotes: 2

Zeyad Etman
Zeyad Etman

Reputation: 2550

I just implemented it using reduce and destructuring:

const [R, G, B] = colors.reduce((acc, cur, indx) => {
    if(cur.length && indx === 0 ) {
        acc.push([cur]);
    } else if(!cur.length) {
        acc[acc.length - 1].push(cur);
    } else {
        acc.push([cur]);
    }

return acc;
}, []);

Upvotes: 1

Luïs
Luïs

Reputation: 2843

If you always want to extract an RGB value, and thus have 3 values in your colors array. You could do something like this:

const colors = [[31236780195925], [], [], [], [], [31236780163157], [], [], [31236780228693], [], [], [], [], []];
const indexes = [];

colors.forEach((color, index) => {
    if (color.length > 0) {
        indexes.push(index);
    }
});

const red = colors.slice(indexes[0], indexes[1]);
const green = colors.slice(indexes[1], indexes[2]);
const blue = colors.slice(indexes[2]);
  • The first loop creates an array of indexes of every array in your colors variable which isn't empty.

  • You can then .slice your array at those indexes to split them apart.


In case you want a more dynamic approach. You could loop over your colors array again and use those indexes to create a new nested array:

const slicedColors = [];

colors.forEach((color, index) => {
    if (color.length > 0) {
        const nextColorIndex = indexes[indexes.indexOf(index) + 1];
        slicedColors.push(colors.slice(index, nextColorIndex));
    }
});

const red = slicedColors[0];
const green = slicedColors[1];
const blue = slicedColors[2];

Upvotes: 0

Related Questions