Search code examples
javascriptnode.jschalk

Get random color inside forEach() in chalk.js


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()
})

Solution

  • 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))
    })