简体   繁体   中英

Create array of Ids from another already existing array

I want to create an array of Ids for each element of an already existing array of unknown size. The tricky part is that I need to have every four elements with the same Id.

For example the new array would be: Assuming the array1 has 20 items, [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5]

I tried doing something with a for loop, but I don't know how I can fill every four elements without overwriting them while iterating.

for(let i=0; i < itemlist.length; i++) {newArray[i] = i; newArray[i] = i;newArray[i] = i;newArray[i] = i;}

You can create an array of one-fourth the size and use flatMap to initialize it with four elements of each index.

 function generateArray(size){ return [...Array(size / 4)].flatMap((_,i)=>Array(4).fill(i + 1)); } console.log(generateArray(20));

You could map the existing array to a function that generates the id from the index in the existing array

 const someArray = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]; const yourArray = someArray.map((el, i) => Math.floor(i / 4) + 1); console.log(yourArray);

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