How to duplicate elements in a js array?

后端 未结 11 540
慢半拍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])
    
    0 讨论(0)
  • 2020-12-03 21:31

    Just splice a little bit.

    var a = [2, 3, 1, 4],
        i = a.length;
    while (i--) {
        a.splice(i, 0, a[i]);
    }
    document.write('<pre>' + JSON.stringify(a, 0, 4) + '</pre>');

    0 讨论(0)
  • 2020-12-03 21:32

    Basically you can use flatMap in ES19

    a = [1, 2, 3, 4];
    a.flatMap(i => [i,i]); // [1, 1, 2, 2, 3, 3, 4, 4]
    

    Also you can customize the repetitions number like this:

    a = [1, 2, 3, 4];
    const dublicateItems = (arr, numberOfRepetitions) => 
        arr.flatMap(i => Array.from({ length: numberOfRepetitions }).fill(i));
    
    dublicateItems(a, 3);
    
    0 讨论(0)
  • 2020-12-03 21:37

    I came across this issue in my application, so I created this function:

    function duplicateElements(array, times) {
      return array.reduce((res, current) => {
          return res.concat(Array(times).fill(current));
      }, []);
    }
    

    To use it, simple pass the array, and the number of times you want the elements to be duplicated:

    duplicateElements([2, 3, 1, 4], 2);
    // returns: [2, 2, 3, 3, 1, 1, 4, 4]
    
    0 讨论(0)
  • 2020-12-03 21:40

    ES6 way of life (based on axelduch's answer)

    const arr = [2, 3, 1, 4].reduce((res, current) => [...res, current, current], []);
    
    console.log(arr);

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