How to populate an array with same elements?

Viewed 264

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 ?

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

With a simple for loop:

const myArr = ['A','B'];

const times = 10;

let newArr = [];
for (let i=0;i<times;i++){
  newArr = newArr.concat(myArr);
}

console.log(newArr)

Oneliner:

const myArr = ['A','B'];
const times = 10;
const len = myArr.length;

const newArr = Array(len*times).fill(0).map( (x,i) => myArr[i%len]);

console.log(newArr)

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

As requested, this would be my approach with loop:

I would use a negative while loop (explanation why) You can also check the methods out to see which method is the fastest one. I made a test here comparing the push method in a for loop and Array.map and also the negative while loop. On my browser the negative while loop was the fastest. If you want to have much more duplicates (e.g. 1000 duplicates) then the difference of the methods will be even larger (benchmark test for 1024 array length and various methods).

It seems that chromium based browsers (Opera, Edge, google chrome) get the fastest results with a negative while loop and for firefox the array.from map function delivers the fastest results.

let myArray = ['A', 'B'];

let k = 10; //array.length^k = new array length

while (--k){
    myArray.push(...myArray);
}

console.log(myArray);

You can simply use push and recursion WITHOUT loops

const newArr = []    
const myArr = ['A','B']

const replicate = n => 
(n === 0 ? [] : newArr.push(...myArr) & replicate(n-1));

replicate(3)
console.log(newArr)

Using Array.prototype.join("") and String.prototype.repeat().

const
    data = ['A','B'],
    result = Array.from(data.join("").repeat(5));

console.log(result);
    

Try

myArr.push('A');

foreach element you want to add.

Related