I would like to ask for efficient way to create such array:
[
1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3
...
n, n, n, n, n, n
]
Every 6 items the number is added 1++.
function createFaces(n){
var array = [];
var l = 1;
while(n > 0){
for(var i = 0; i < 6; i++){
array.push(l)
}
l++;
n--;
}
return array;
}
You could use Array.from with a function for the value.
function createFaces(n) {
return Array.from({ length: 6 * n }, (_, i) => Math.floor(i / 6) + 1);
}
console.log(createFaces(7));
.as-console-wrapper { max-height: 100% !important; top: 0; }
To create an array of size n filled with value v, you can do
Array(n).fill(v);
In the context of your function:
function createFaces(n){
var array = [];
for (var i=1; i <= n; i++) {
array = array.concat(Array(6).fill(i));
}
return array;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With