简体   繁体   中英

DRYing Function that multiplies array

I have an array of 100 elements, that I have broken into 10 smaller arrays in order to quadruplicate the original 100 elements into an array of 400.

I am currently using :

function quadulator(arrChunks){
let a = []; 
let b = [];

    for(var i = 0; i< arrChunks.length;++i){
        a.push(arrChunks[i]);
        a.push(arrChunks[i]);
        b.push(arrChunks[i]);
        b.push(arrChunks[i]);
}  

return a.concat(b);

}
let group1 = quadulator(grid100[0]);
let group2 = quadulator(grid100[1]);
let group3 = quadulator(grid100[2]);
let group4 = quadulator(grid100[3]);
let group5 = quadulator(grid100[4]);
let group5 = quadulator(grid100[5])

let newArr = group1.concat(group2,group3,group4,group5);

This does exactly what I want it to do ,but Im looking for a way to eliminate the repetition.

The reason I am splitting it up into multiple parts is because I need the element of index 0 from the original array, to repeat itself in the indexes of 0,1,20, and 21 of the new array, along with every other element to follow this pattern.

You can improve the quadulator function by noticing that a and b are the same. You can create a single array at once that represents both of them with Array.from , and then spread that array twice.

Then, with your group s, you can map grid100 by the quadulator function, and spread it into [].concat to flatten:

function quadulator(arrChunks) {
  const chunksDoubled = Array.from(
    { length: arrChunks.length * 2 },
    (_, i) => arrChunks[Math.floor(i / 2)]
  );
  return [...chunksDoubled, ...chunksDoubled];
}
const newArr = [].concat(...grid100.map(quadulator));

Demo:

 const grid100 = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ]; function quadulator(arrChunks) { const chunksDoubled = Array.from( { length: arrChunks.length * 2 }, (_, i) => arrChunks[Math.floor(i / 2)] ); return [...chunksDoubled, ...chunksDoubled]; } const newArr = [].concat(...grid100.map(quadulator)); console.log(newArr); 

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