Reputation: 8484
I want to generate the following array:
[3, 3, 3, 3, 4, 4, 5, 5, 5]
there are 3 different values that should repeat m
, n
, and k
times. What is the easiest way to do that?
If I do Array(m + n + k).fill(...).fill(...).fill(...)
the start and end points in later fill
calls look not very straightforward.
Upvotes: 2
Views: 258
Reputation: 3317
var arrValues = [3,4,5];
var arrRepeats = [4,2,3];
var arr = [];
for(var i =0; i< arrRepeats.length;i++){
arr.push(Array(arrRepeats[i]).fill(arrValues[i]));
}
console.log(arr)
Or
var arrValues = [3,5,4]; var arrRepeats = [4,2,3]; let arr = []; for(var i =0; i< arrRepeats.length; i++){ for(var j=0; j<arrRepeats[i];j++){ arr.push(arrValues[i]); } } console.log(arr)
Or you can do that if you wanna generate arrays and combine them
var arrValues = [3,5,4]; var arrRepeats = [4,2,3]; // m, n, k var mainArr = []; for(var i =0; i< arrRepeats.length; i++){ var arr = []; for(var j =0; j < arrRepeats[i]; j++){ arr.push(j); arr.fill(arrValues[i]); } mainArr.push(arr); } console.log(mainArr)
Upvotes: 0
Reputation: 192317
Create an array of values
, and an array of repeat
. Iterate the values
with Array.map()
, and return a new array filled with the values. Flatten by spreading into Array.concat()
:
const values = [3, 4, 5];
const repeat = [4, 2, 3];
const arr = [].concat(...values.map((v, i) => new Array(repeat[i]).fill(v)));
console.log(arr);
Upvotes: 0
Reputation: 24571
Generate the arrays separately and then combine them into one final array
[
...Array(4).fill(3),
...Array(2).fill(4),
...Array(3).fill(5)
]
Upvotes: 3