mirror of
https://github.com/Fechin/reference.git
synced 2026-11-20 21:23:11 +03:00
927 B
927 B
title, tags, layout
| title | tags | layout | |||||
|---|---|---|---|---|---|---|---|
| How to repeat an array in JavaScript |
|
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]