How to duplicate elements in a js array?

后端 未结 11 582
慢半拍i
慢半拍i 2020-12-03 20:46

Whats the easiest way (with \"native\" javascript) to duplicate every element in a javascript array?

The order matters.

For example:



        
11条回答
  •  不知归路
    2020-12-03 21:30

    0/2  =  0    =  0  |0  =  0
    1/2  =  0.5  =  0.5|0  =  0
    2/2  =  1    =  1  |0  =  1
    3/2  =  1.5  =  1.5|0  =  1
    4/2  =  2    =  2  |0  =  2
    5/2  =  2.5  =  2.5|0  =  2
    6/2  =  3    =  3  |0  =  3
    7/2  =  3.5  =  3.5|0  =  3
    

    Treat |0 as Math.floor


    In code this could look like this:

    for (let i = 0; i < a.length * 2; i++) {
      a[i] = a[i / 2 | 0]
    }
    

    Because immutability is preferable, one could do something like this:

    function repeatItems(a, n) {
      const b = new Array(a.length * n)
      for (let i = 0; i < b.length; i++) {
        b[i] = a[i / n | 0]
      }
      return b
    }
    

    Unreadable ES6 spaghetti code:

    const repeatItems = (a, n) => Array.from(Array(a.length * n), (_, i) => a[i / n | 0])
    

提交回复
热议问题