Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JS array of repeated value

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;
}
like image 289
Bartek Avatar asked May 29 '26 07:05

Bartek


2 Answers

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; }
like image 63
Nina Scholz Avatar answered May 30 '26 21:05

Nina Scholz


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;
}
like image 28
James Avatar answered May 30 '26 19:05

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!