Duplicate an array an arbitrary number of times (javascript)

前端 未结 9 1181
臣服心动
臣服心动 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 18:08

    You can do:

    var array = ['1','2','3'];
    
    
    function nplicate(times, array){
          //Times = 2, then concat 1 time to duplicate. Times = 3, then concat 2 times for duplicate. Etc.
         times = times -1;
         var result = array;
    
        while(times > 0){
            result = result.concat(array);
            times--;
        }
    
        return result;
    }
    
    console.log(nplicate(2,array));
    

    You concat the same array n times.

    Use concat function and some logic: http://www.w3schools.com/jsref/jsref_concat_array.asp

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

    Basic but worked for me.

    var num = 2;
    
    while(num>0){
    array = array.concat(array);
    num--}
    
    0 讨论(0)
  • 2021-01-17 18:11

    if you are inside a loop you can verify the current loop index with the array length and then multiply it's content.

    let arr = [1, 2, 3];
    
    if(currentIndex > arr.length){ 
      //if your using a loop, make sure to keep arr at a level that it won't reset each loop
    
      arr.push(...arr);
    
    }
    

    Full Example: https://jsfiddle.net/5k28yq0L/

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