I am trying to populate items of an array with same items and order.
As an example, I have an array like this, with two string elements.
const myArr = ['A','B'];
What I'm trying to do is something like that. I need to populate items 10 times or more. I'm thinking of a for loop but maybe there are more efficient alternatives.
const myArr2 = ['A','B','A','B','A','B','A','B','A','B'];
How can I achieve this with Vanilla JS ?
You could take a standard approach with an array constructor, the length, a filling and flattening.
const
pattern = ['A','B'],
times = 5,
result = Array(times).fill(pattern).flat();
console.log(...result);
If you're not opposed to loops, you could use the spread syntax to push
the contents of your array a number of times.
const myArr = ['A', 'B'];
let myArr2 = [];
for (let i = 0; i < 5; i++) {
myArr2.push(...myArr);
}
console.log(myArr2);
If you don't like loops, Array.map
could work.
const myArr = ['A', 'B'];
let myArr2 = Array.from({ length: 10 })
.map((x, i) => x = myArr[i % 2]);
console.log(myArr2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With