简体   繁体   中英

How to repeat the first element in an array each 2 index

I have an array of arrays:

[
  ['1', 'a', 'b', 'c', 'd', 'e', ​​'f', 'g', 'h'],
  ['2', 'a', 'b', 'c', 'd', 'e', ​​'f', 'g', 'h'],
  ...
]

and I need the first element of the arrays to be repeated every 2 positions in each array:

[
  ['1', 'a', '1', 'b', '1', 'c', '1', 'd', '1', 'e', ​​'1', 'f', ' 1 ',' g ',' 1 ',' h '],
  ['2', 'a', '2', 'b', '2', 'c', '2', 'd', '2', 'e', ​​'2', 'f', ' 2 ',' g ',' 2 ',' h '],
  ...
]

How can I do this?

You could take the first element out of the array and take Array#flatMap for the wanted pairs.

 const getPaired = ([zero, ...a]) => a.flatMap(v => [zero, v]); var array = ['1', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], result = getPaired(array); console.log(...result);

You could set up some kind of for loop like this:

for(var i = 0; i < arrayName.length; i++){
    if(i%2 == 0){
        arrayName[i] = arrayName[0];  //puts the first element every 2 index's
    }else{
        //put whatever else needs to be in between
    }
}

Use Array.map() and Array.reduce() :

 let arr = [ ['1', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',], ['2', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',], ] let res = arr.map(el => { let firstEl return el.reduce((acc,cur,idx) => { firstEl = idx == 0? cur: firstEl if(idx > 1){ acc.push(firstEl) } acc.push(cur) return acc }, []) }) console.log(res)

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