简体   繁体   中英

how to repeat different element in an array?

suppose there is an array

[1, 2, 3, 4]

I want first element repeat 3 times, the rest elements repeat 2 times.

at the end I want to have something like this [1,1,1,2,2,3,3,4,4]

I know that we can write a dummy loop. But is there any better way to do that?

You can use flatMap() . Create array of length 2 or 3 based of index and fill() it with element.

 let arr = [1, 2, 3, 4] let res = arr.flatMap((x,i) => Array(i === 0 ? 3 : 2).fill(x)) console.log(res) 

For more general solution create a function which takes three parameters.

const createArray = (arr,times,obj) => arr.flatMap((x,i) => Array(obj[i] || times).fill(x))

arr : Given array whose values will be repeated.
times : No of times every element will be repeated.
obj : An object which have keys as index and value no of times the element at that index will repeat.

 const createArray = (arr,times,obj) => arr.flatMap((x,i) => Array(obj[i] || times).fill(x)) let arr = [1,2,3,4]; const obj = {0:5,3:3} let res = createArray(arr,2,obj); //1 will be repeated 5 times. 4 will be repeated 3 times and all others two tiems console.log(res) 

Use reduce and check the index, then use spreading:

 const arr = [1, 2, 3, 4]; const res = arr.reduce((acc, curr, idx) => { acc.push(curr, curr); if (idx == 0) acc.push(curr); return acc; }, []); console.log(res); 
 .as-console-wrapper { max-height: 100% !important; top: auto; } 

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