Duplicate an array an arbitrary number of times (javascript)

前端 未结 9 1179
臣服心动
臣服心动 2021-01-17 17:35

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

相关标签:
9条回答
  • 2021-01-17 17:44

    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);
    }
    
    0 讨论(0)
  • 2021-01-17 17:45

    Keep it short and sweet

    function repeat(a, n, r) {
        return !n ? r : repeat(a, --n, (r||[]).concat(a));
    }
    
    console.log(repeat([1,2,3], 4)); // [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
    

    http://jsfiddle.net/fLo3uubk/

    0 讨论(0)
  • 2021-01-17 17:50

    I think you will have to write your own function, try this:

    function dupArray(var n,var arr){
    var newArr=[];
    for(var j=0;j<n;j++)
        for(var i=0;i<arr.length;i++){
            newArr.push(arr[i]);
        }
    return newArr;
    }
    
    0 讨论(0)
  • 2021-01-17 17:55
    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.

    0 讨论(0)
  • 2021-01-17 18:01

    A rather crude solution for checking that it duplicates... You could check for a variation of the length using modulus:

    Then if it might be, loop over the contents and compare each value until done. If at any point it doesn't match before ending, then it either didn't repeat or stopped repeating before the end.

    if (array2.length % array1.length == 0){
        // It might be a dupe
        for (var i in array2){
            if (i != array1[array2.length % indexOf(i)]) { // Not Repeating }
        }
    }
    
    0 讨论(0)
  • 2021-01-17 18:04

    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.

    0 讨论(0)
提交回复
热议问题