how to make an iterative array from two array

Tags:



I have a cmyk array which is :

cmykColor = [[0,1,0,1],[0,0,1,1],[0,0,0,1]]

and the other one is the number array which is:

arrGeo = [4,2,1]

I want to have an array which has iterative cmyk respect to arrGeo numbers which means:

cmykArray = [
[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,],
[0,0,1,1,0,0,1,1],
[0,0,0,1]
]

and this is my code to make it :

for (let i = 0; i < arrGeo.length; i++) {
      var cmyk = [];
      var cmykArray = [];
      for (let j = 0; j < arrGeo[i].length; j++) {
        for (let k = 0; k < 4; k++) {
         cmyk = cmyk.concat(cmykColor[i][k]);
        console.log(hex[i]);
         }
      }
       cmykArr.push(cmyk);
    }

Answer

You could map with another loop for the wanted count.

const
    cmykColor = [[0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 0, 1]],
    arrGeo = [4, 2, 1],
    result = cmykColor.map((a, i) => {
        let c = arrGeo[i],
            t = [];
        while (c--) t.push(...a);
        return t;
    });

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


Source: stackoverflow