3

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;
}
7
  • How many rows would you like to add? Commented Jan 30, 2018 at 20:48
  • It doesn't matter (for example 6) Commented Jan 30, 2018 at 20:49
  • 1
    What is wrong with your implementation? Commented Jan 30, 2018 at 20:50
  • It is not wrong but I try to find more efficient way. Commented Jan 30, 2018 at 20:51
  • The way you have written traverses through each target element array exactly once, with minimal overhead. You could make it slightly more efficient (maybe) by making it a single loop from i=6 through i=6*n+5, and pushing i/6 to the array. Similarly, you could eliminate one of your outer indices. That's all nearly pointless micro-optimization though. Commented Jan 30, 2018 at 20:51

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

nice approach with Array.from
1

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

2 Comments

This also creates an array of arrays, which isn't quite what the OP's code does. To do the exact same thing, the line inside the for loop should be array = array.concat(Array(6).fill(i));
Oops, I saw an array of arrays where one didn't exist. Yes to concat.
0

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.