Search code examples
javascriptarrayshexrgb

how do I convert a large array of rgb values to a hex array


their current format is [r,g,b,r,g,b,...] I need an array of hex values like this [#rgb,#rgb,...] its specifically an array of 797 arrays of 1176 items each it should be 797 arrays of 392 items each I found functions to convert rgb to hex if formatted like this [[r,g,b][r,g,b],...] but the array I have is not broken into smaller chunks this way so ether something that can convert the whole thing of something that a can break it up into sets of three I can just use a foreach loop im unsure how to approach this


Solution

  • Something like this?

    It is not clear if you had an array of arrays

    const rgbToHex = (r, g, b) => `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
    
    const convertArrayToHexColors = (array) => array.map(subArray => 
      Array.from({ length: subArray.length / 3 }, (_, i) => 
        rgbToHex(subArray[i * 3], subArray[i * 3 + 1], subArray[i * 3 + 2])
      )
    );
    
    
    const hexColorArray = convertArrayToHexColors(exampleArray);
    console.log(hexColorArray)
    <script>
    const exampleArray = [
        [255, 0, 0, 0, 255, 0, 0, 0, 255], 
        [128, 128, 128, 192, 192, 192, 64, 64, 64] 
    ];
    </script>