简体   繁体   English

将数组相乘的DRYing函数

[英]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. 我有一个由100个元素组成的数组,为了将原来的100个元素加倍成400个数组,我将其分成10个较小的数组。

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. 之所以将其拆分为多个部分,是因为我需要原始数组中索引为0的元素,以便在新数组的索引0、1、20和21中重复其自身,以及所有其他元素。遵循这种模式。

You can improve the quadulator function by noticing that a and b are the same. 您可以通过注意ab相同来改善quadulator功能。 You can create a single array at once that represents both of them with Array.from , and then spread that array twice. 您可以使用Array.from一次创建一个代表它们的单个数组,然后将该数组传播两次。

Then, with your group s, you can map grid100 by the quadulator function, and spread it into [].concat to flatten: 然后,使用group s,可以通过quadulator函数map grid100,并将其展开到[].concat进行展平:

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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM