How to generate a series of unique HEX colors in JavaScript

1 Answer

0 votes
// Generate N unique random HEX colors (#RRGGBB)
function generateRandomUniqueHexColors(count) {
  // A Set automatically ensures uniqueness
  const colors = new Set();

  // Keep generating until we have the desired amount
  while (colors.size < count) {
    // Create 3 random bytes (R, G, B)
    const bytes = new Uint8Array(3);
    crypto.getRandomValues(bytes); // secure randomness

    // Convert each byte to a 2-digit hex string and join them
    const hex = `#${[...bytes]
      .map(v => v.toString(16).padStart(2, "0"))
      .join("")}`;

    // Add to the Set (duplicates are ignored automatically)
    colors.add(hex);
  }

  // Convert the Set back to a normal array
  return [...colors];
}

// Example usage
const colors = generateRandomUniqueHexColors(12);

console.log("Generated HEX colors:");
colors.forEach(c => console.log(c));


/*
run:

Generated HEX colors:
#3a12ec
#fec8b4
#b88cfa
#1c080f
#4f4d12
#73217e
#45e139
#4288b1
#9cc21c
#06ee0b
#efdd1b
#652526

*/

 



answered Aug 24 by avibootz
...