Whats the easiest way (with \"native\" javascript) to duplicate every element in a javascript array?
The order matters.
For example:
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]