How to duplicate elements in a js array?

后端 未结 11 551
慢半拍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: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]
    

提交回复
热议问题