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