Duplicate an array an arbitrary number of times (javascript)

前端 未结 9 1315
臣服心动
臣服心动 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

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

提交回复
热议问题