Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 283
Kelsey Zhou Avatar asked Mar 24 '26 04:03

Kelsey Zhou


2 Answers

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)
like image 102
Maheer Ali Avatar answered Mar 26 '26 18:03

Maheer Ali


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; }
like image 26
Jack Bashford Avatar answered Mar 26 '26 19:03

Jack Bashford



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!