Search code examples
javascriptarraysnode.js

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;

Solution

  • Here's a fairly concise, non-recursive way of replicating an array an arbitrary number of times:

    function replicateArray(array, n) {
      // Create an array of size "n" with undefined values
      var arrays = Array.apply(null, new Array(n)); 
    
      // Replace each "undefined" with our array, resulting in an array of n copies of our array
      arrays = arrays.map(function() { return array });
    
      // Flatten our array of arrays
      return [].concat.apply([], arrays);
    }
    
    console.log(replicateArray([1,2,3],4)); // output: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
    

    What's going on?

    The first two lines use apply and map to create an array of "n" copies of your array.

    The last line uses apply to flatten our recently generated array of arrays.

    Seriously though, what's going on?

    If you haven't used apply or map, the code might be confusing.

    The first piece of magic sauce here is the use of apply() which makes it possible to either pass an array to a function as though it were a parameter list.

    Apply uses three pieces of information: x.apply(y,z)

    • x is the function being called
    • y is the object that the function is being called on (if null, it uses global)
    • z is the parameter list

    Put in terms of code, it translates to: y.x(z[0], z[1], z[2],...)

    For example

    var arrays = Array.apply(null, new Array(n));
    

    is the same as writing

    var arrays = Array(undefined,undefined,undefined,... /*Repeat N Times*/);
    

    The second piece of magic is the use of map() which calls a function for each element of an array and creates a list of return values.

    This uses two pieces of information: x.map(y)

    • x is an array
    • y is a function to be invoked on each element of the array

    For example

    var returnArray = [1,2,3].map(function(x) {return x + 1;});
    

    would create the array [2,3,4]

    In our case we passed in a function which always returns a static value (the array we want to duplicate) which means the result of this map is a list of n copies of our array.