Files
reference/note/javascript/array/repeat-an-array.md
T
2022-10-18 11:37:51 +08:00

927 B

title, tags, layout
title tags layout
How to repeat an array in JavaScript
JavaScript
ES6
one-line
js
Array
note

In this Article we will go through how to repeat an array only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

const repeat = (arr, n) => [].concat(...Array(n).fill(arr));

Parameters arr is an array.

Or

const repeat = (arr, n) => Array(n).fill(arr).flat();

Or

const repeat = (arr, n) => Array(arr.length * n).fill(0).map((_, i) => arr[i % arr.length]);

Or

const repeat = (arr, n) => Array.from({ length: arr.length * n }, (_, i) => arr[i % arr.length]);

Example

repeat([1, 2, 3], 3);       // [1, 2, 3, 1, 2, 3, 1, 2, 3]