4

I'm trying to create an array with 3 elements without using for loops, so the code will be a single line (or single statement). What I want to do is creating an array of 3 elements and each element should be random number from 0 to 255 (0 and 255 will be included).

let colors = new Array(3).map((v) => Math.floor(Math.random()*256));

But this code doesn't work, I guess it's because each element is undefined and .map array property can't map undefined elements. What's your suggestions?

M. Çağlar TUFAN
  • 626
  • 1
  • 7
  • 21
  • 1
    Is there a reason why you expect `new Array()` to create 3 elements? (I'm guessing you may have forgotten to add `3` to `new Arrray(3)` and that you may be facing [this issue](https://stackoverflow.com/questions/53491943/why-do-i-need-to-copy-an-array-to-use-a-method-on-it/53491990#53491990)?) – Nick Parsons May 19 '21 at 12:32
  • @NickParsons Oh, yeah. I forgot it. I have tried that with ``new Array(3)``. – M. Çağlar TUFAN May 19 '21 at 14:19

6 Answers6

7

Array.from() is something you are looking for:

const res = Array.from({length: 3}, _ => Math.floor(Math.random()*256))
console.log(res)
ulou
  • 5,542
  • 5
  • 37
  • 47
3

You can try using Array.from() specifying the array-like objects (objects with a length property and indexed elements) of the array as first parameter and the arrow function to fill the array with random values in that range as the second parameter:

let colors = Array.from({length: 3}, () => Math.floor(Math.random() * 256));
console.log(colors);
Mamun
  • 66,969
  • 9
  • 47
  • 59
2

Without usage of Array.from

[0,0,0].map(() => Math.floor(Math.random() * 256))

One more ridiculous approach :) just for fun:

var result =
  Math.floor(Math.random() * (Math.pow(2, 24) + 1)) // generate random number between zero and 2^24
    .toString(2) // convert it to binary representation string
    .padStart(24, '0') // ensure that length is 24
    .match(/.{1,8}/g) // split digits to three groups of length 8
    .map(i => parseInt(i, 2)) // parse it back

console.log(result)
  • 2^24 will have 24 digits in binary representation, so we'll be able to split it in 3 groups of 8 digits each.
  • padding is necessary to ensure amount of digits in a binary representation
Monsieur Merso
  • 1,459
  • 1
  • 15
  • 18
0

Something less extensible but more straight-forward:

let colors = [Math.floor(Math.random()*256),Math.floor(Math.random()*256),Math.floor(Math.random()*256)];
console.log(colors)
Ahmad Habib
  • 2,053
  • 1
  • 13
  • 28
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

You can use Array.from({length: 3}, () => Math.floor(Math.random() * 256));

0

Just follow this, you'll be fine!

const colors = Array.from({length: 5 }, () => Math.floor(Math.random()*256))

console.log(colors)