简体   繁体   中英

Create new array from existing array JavaScript by repeating the original array

In my project I have a requirement to create a new array form existing array. For example if the original array is like

var arr1 = [1,2,3,4,5];

I need to create the new array of length 7 means it should be like below

var newArr = [1,2,3,4,5,1,2];

The new array length is dynamic, if the length is going to 9 means it should be like

var newArr = [1,2,3,4,5,1,2,3,4];

and if it going to be 15 means it should be like below

var newArr = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]

The new array should be created by repeating the original array based on the dynamic length.

Here's one option, using Array.from and modulo:

 var arr1 = [1,2,3,4,5]; const makeNewArr = length => Array.from( { length }, (_, i) => arr1[i % arr1.length] ); console.log(makeNewArr(7));

You can do that using a simple for loop.

 function generateArray(length) { var arr = []; var max = 5; var value = 1; for (var i = 1; i <= length; i++) { if (value > max) { value = value % max; } arr.push(value); value++; } return arr; } // Using toString() to display output in one line. console.log(generateArray(7).toString()); console.log(generateArray(9).toString()); console.log(generateArray(15).toString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM