Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate an array with same elements?

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 ?

like image 667
Çetin Avatar asked Dec 31 '22 15:12

Çetin


2 Answers

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);
    
like image 120
Nina Scholz Avatar answered Jan 02 '23 05:01

Nina Scholz


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);
like image 24
D M Avatar answered Jan 02 '23 04:01

D M