Reputation: 31
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;
}
Upvotes: 3
Views: 76
Reputation: 33726
Using Array.prototype.map()
function
let fill = function(length, threshold) {
let i = 1;
return new Array(length * threshold).fill().
map((_, idx) =>
(idx + 1) % threshold === 0 ? i++ : i);
};
console.log(fill(7, 6));
Upvotes: 0
Reputation: 22247
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;
}
Upvotes: 1
Reputation: 23379
If you want a flat array...
function createFaces(n, x){
for(var i=0, a=[]; i<n; a.push(...Array(x).fill(i)) && i++){}
return a;
}
console.log(createFaces(7, 6));
Upvotes: 0
Reputation: 386634
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; }
Upvotes: 2