Reputation: 63
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?
Upvotes: 2
Views: 613
Reputation: 36564
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)
Upvotes: 6
Reputation: 44087
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; }
Upvotes: 2