1

Trying to generate randomly html color codes but not working. So, How to generate it in the for loop. I have tried in google and stackoverflow, but not able to find out the solution. If anyone knows please help to find the solution.

Example totalColor should be like ['#CD5C5C','#F08080','#FA8072','#E9967A',.....upto 10]

app.component.ts:

getrandomcolor(length) {
    let letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < length; i++) {
      color += letters[Math.floor(Math.random() * 16)];
      this.totalColor.push(color);
    }

    console.log(this.totalColor);
  }

Demo : https://stackblitz.com/edit/angular-ivy-kvdhev?file=src%2Fapp%2Fapp.component.ts

EMahan K
  • 417
  • 1
  • 19
  • To start, `this.totalColor.push(color);` should be outside (after) the for loop. You are currently pushing incomplete color codes. – juzraai Aug 05 '22 at 09:43

8 Answers8

3

Check this out

function createRandomString(length) {
  let chars = "0123456789ABCDEF", color="";
  for (let i = 0; i < length; i++) {
     color += chars[Math.floor(Math.random() * 16)];
  }
  return '#'+color;
}
console.log(createRandomString(6))
Amaarockz
  • 4,348
  • 2
  • 9
  • 27
3
  1. move the color variable inside the first loop.
  2. create a nested for loop inside the first for loop that iterates 6 times, each time concatenating the color string with an new character.

const totalColor = []

function getrandomcolor(length) {
  let letters = '0123456789ABCDEF';

  for (let i = 0; i < length; i++) {
    let color = '#';
    for (let j = 0; j < 6; j++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    totalColor.push(color);
  }
  console.log(totalColor);
}

getrandomcolor(10)
tadej
  • 86
  • 7
1

You have mistake here, you push while getting each hex letter which will be incorrect. Also the hex color length (CSS) should be:

  • 3 (shortand)
  • 6 (RRGGBB)
  • 8 (RRGGBBAA)

Now, in this sample I use regular 6 digit hex code value, to fix it, the color should be added to array after loop:

import { Component, VERSION, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;

  public totalColor = [];

  ngOnInit(): void {
    this.getrandomcolor(10);
  }

  getrandomcolor(length) {
    for(let x = 0; x < length; x++){
      let letters = '0123456789ABCDEF';
      let color = '#';
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      console.log(color);
      this.totalColor.push(color);
    }

  }
}


owenizedd
  • 1,187
  • 8
  • 17
0

There is already a solution on stackoverflow

export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;

  public totalColor: string[] = [];

  ngOnInit(): void {
    this.getrandomcolor(10);
  }

  getrandomcolor(length) {
    for (let i = 0; i < length; i++) {
      this.totalColor.push(this.randomColor());
    }

    console.log(this.totalColor);
  }

  randomColor(): string {
    return (
      '#' + (0x1000000 + Math.random() * 0xffffff).toString(16).substr(1, 6)
    );
  }
}

You can view it on StackBlitz

Oth Mane
  • 1
  • 1
0

Use RGB value like:

function giveRandomColors(NumberofColors) {
  let randomColors = [];
  for (let i = 0; i < NumberofColors; i++) {
    randomColors.push({
      r: Math.floor(Math.random() * 255),
      g: Math.floor(Math.random() * 255),
      b: Math.floor(Math.random() * 255),
    });
  }
  return randomColors;
}
console.log(giveRandomColors(10));

Hope it helps.

Mohammed Shahed
  • 840
  • 2
  • 15
0

One liner using Array.from:

const generateRandomColors = (amount) => Array.from(
  { length: amount },
  () => '#' + (Math.floor(Math.random() * 16777215))
                .toString(16).toUpperCase()
                .padStart(6, 0)
)

console.log(generateRandomColors(10))
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore this */

Explanation:

  • Math.floor() converts our decimal into integer,
  • 16777215 is 0xffffff in hex. This is our max number that we want to pull,
  • toString(16) converts our pulled number to hex,
  • padStart(6, 0) fills our string with 0 at start, if our pulled number is to small (smaller than 0x100000).
ulou
  • 5,542
  • 5
  • 37
  • 47
0

As per my understanding, You want to get the array of random color codes based on the array length passed as a function parameter. If Yes, You can easily achieve it by creating the 6 char color codes inside the function itself.

Live Demo :

const totalColor = [];

function getrandomcolor(length) {
  let letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < length; i++) {
    for (let j = 0; j < 6; j++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    totalColor.push(color);
    color = '#';
  }
  return totalColor;
}

console.log(getrandomcolor(10));
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
0

Here is my answer with some references if you need:

function randomColorsGenerator(length) {
    let randomColorsArray = [];

    for (let i = 0; i < length; i++) {
        let color = Math.random(); // This line generates pseudo-random number that's greater than or equal to 0 and less than 1.
        color = Math.random().toString(16); // This line converts number to string but based on 16(0,1,2, ... , E, F). 
        color = Math.random().toString(16).substring(2, 8).toUpperCase(); // This line extracts the part we need(the first 6 character after character in position 2) and then converts everything to UPPERCASE 
        randomColorsArray.push(color);// This line adds the generated color to the randomColorsArray
    }
    console.log(randomColorsArray); // This line prints the randomColorsArray in console
}

randomColorsGenerator(10);

For Math.random() see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

For toString(16) see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString#parameters (You should read about "radix")

For substring(x, y) see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring#try_it

For toUpperCase() see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase#try_it

Narges
  • 39
  • 3