0

I am trying to create an array alternating between 2 different values with a predetermined length.

Example:

conts value1 = 1;
const value2 = 2; 
cont length = 6; 

//desired output
const array1 = [1, 2, 1, 2, 1, 2];

  • First, it looks like you have an error in your code "const". Second, could you add the resulting values and the expected values to see what are you trying to achieve? – Andrés Chandía Mar 17 '20 at 21:13

4 Answers4

2

You can create the array using Array.from with the desired length and map it to have the desired values :

const value1 = 1;
const value2 = 2; 
const length = 6; 

const result = Array.from({ length }).map((e, ndx) => ndx % 2 ? value2 : value1); 

console.log(result);
Taki
  • 17,320
  • 4
  • 26
  • 47
0

Try with:

var repeated = new Array(3).fill([1, 2]).flat();

Or more general:

function repeat(n, value){
    return new Array(n).fill(value).flat();
}

result = repeat(3, [1, 2]);

Credits: https://stackoverflow.com/a/54935305/4628597

Alvin Sartor
  • 2,249
  • 4
  • 20
  • 36
0

An easy beginner solution would be something like this:

function createArray(value1, value2, length){
    var array = new Array()
    for(var i=0; i<length;i++){ 
          if(i%2 == 0){
           array.push(value1);
          }else{
           array.push(value2);
          }
    return array;
    }
}
naman
  • 46
  • 1
  • 5
0

You could take an array of values in the wanted order and use a closure over the index of the values array adjusted by taking the remainder with the length of the values array.

const values = [1, 2],
      length = 6,
      result = Array.from({ length }, (i => _ => values[i++ % values.length])(0)); 

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392