Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate an array an arbitrary number of times (javascript)

Let's say I'm given an array. The length of this array is 3, and has 3 elements:

var array = ['1','2','3'];

Eventually I will need to check if this array is equal to an array with the same elements, but just twice now. My new array is:

var newArray = ['1','2','3','1','2','3'];

I know I can use array.splice() to duplicate an array, but how can I duplicate it an unknown amount of times? Basically what I want is something that would have the effect of

var dupeArray = array*2;
like image 635
dragonbanshee Avatar asked May 14 '15 03:05

dragonbanshee


People also ask

How do you duplicate an array in Javascript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.

How do you repeat an array and time?

In Python, if you want to repeat the elements multiple times in the NumPy array then you can use the numpy. repeat() function. In Python, this method is available in the NumPy module and this function is used to return the numpy array of the repeated items along with axis such as 0 and 1.

Can array have duplicate values Javascript?

To check if an array contains duplicates: Pass the array to the Set constructor and access the size property on the Set . Compare the size of the Set to the array's length. If the Set contains as many values as the array, then the array doesn't contain duplicates.


2 Answers

const duplicateArr = (arr, times) =>
    Array(times)
        .fill([...arr])
        .reduce((a, b) => a.concat(b));

This should work. It creates a new array with a size of how many times you want to duplicate it. It fills it with copies of the array. Then it uses reduce to join all the arrays into a single array.

like image 136
Milesman34 Avatar answered Oct 12 '22 19:10

Milesman34


The simplest solution is often the best one:

function replicate(arr, times) {
     var al = arr.length,
         rl = al*times,
         res = new Array(rl);
     for (var i=0; i<rl; i++)
         res[i] = arr[i % al];
     return res;
}

(or use nested loops such as @UsamaNorman).

However, if you want to be clever, you also can repeatedly concat the array to itself:

function replicate(arr, times) {
    for (var parts = []; times > 0; times >>= 1) {
        if (times & 1)
            parts.push(arr);
        arr = arr.concat(arr);
    }
    return Array.prototype.concat.apply([], parts);
}
like image 26
Bergi Avatar answered Oct 12 '22 20:10

Bergi