Home » Javascript » javascript – Get random color inside forEach() in chalk.js

javascript – Get random color inside forEach() in chalk.js

Posted by: admin February 24, 2020 Leave a comment

Questions:

I am running a forEach() loop, and I need to console.log(). But I want to get a different color for each iteration. I went trhough docs, but couldn’t find anything. Is there any way possible to achieve the same?

let arr = ["a", "ab, "abc"]
arr.forEach(arr, e => {
  console.log(chalk.red(e)) //maybe something like - chalk.randColor()
})
How to&Answers:

You can try something like this:

// Create an array of possible colors
const color = ['red', 'green', 'blue', 'magenta', 'cyan', 'gray'];
let arr = ["a", "ab", "abc"]
arr.forEach(arr, e => {
  // and get a random color name from the array
  // and call the function on it
  console.log(chalk[color[Math.floor(Math.random() * color.length)]](e))
})

Answer:

You can define an array of strings (all supported colors)

const colors = ['red', 'blue', 'green'];

Then in each iteration get a random color and use chalk[color]

let arr = ["a", "ab", "abc"];
const getRandomColor = (str) => {
  const colors = ["red", "blue", "green"];
  console.log(chalk[colors[Math.floor(Math.random() * colors.length)]](str));
};

arr.forEach(getRandomColor);

Answer:

you can use chalk.rgb with randomizer value to give all level of combination colors to you.

let arr = ["a", "ab, "abc"]
const rdClr = () => Math.floor(Math.random() * 255);
const randomClor = str => chalk.rgb(rdClr(), rdClr(), rdClr())(str);
arr.forEach(arr, e => {
  console.log(randomClor(arr + '%s'));
});

Answer:

These two functions provide much bigger range of different colors randomly:

// Using chalk.hex()
const randColorHex = (msg) => {
  chalk.hex('#' + (Math.random() * 0xFFFFFF << 0).toString(16))(msg);
}

// Using chalk.rgb()
const randColorRgb = (msg) => {
  const rand = () => Math.floor(Math.random() * 255);
  chalk.rgb(rand(), rand(), rand())(msg);
}

// Usage
let arr = ["a", "ab", "abc"];

arr.forEach(item => console.log(randColorHex(item)));
arr.forEach(item => console.log(randColorRgb(item)));

Answer:

If you use randojs.com, the randomness can be simpler and more readable, like this:

var array = ["a", "ab", "abc"], colors = ['red', 'green', 'blue', 'magenta', 'cyan', 'gray'];

array.forEach((item, i) => console.log(chalk[rando(colors).value](i)));

If you want to use this code, just make sure this is in the head tag of your html document:

<script src="https://randojs.com/1.0.0.js"></script>