Bartek
Bartek

Reputation: 31

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;
}

Upvotes: 3

Views: 76

Answers (4)

Ele
Ele

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

James
James

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

I wrestled a bear once.
I wrestled a bear once.

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

Nina Scholz
Nina Scholz

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

Related Questions