【问题标题】:push to target inner arrays from origin array depending on array index根据数组索引从原始数组推送到目标内部数组
【发布时间】:2020-04-20 16:05:15
【问题描述】:

我有一个原始数组,一个简单的列表(“内容”)。我想遍历它并将内容输出到容器数组内的一系列新数组中,每个新数组对应一个系列的增量,具有给定的限制。

这将是起源: var content = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

我尝试了各种方法。这是我的最新版本:

let buildAndFill = function (content, n) {
    let container = [];
    let innerArrayCounter = 0;
    for (i = 0; i < n; i++) { 
        // for each iteration up to n, create inner arrays and push them to container
        container.push([]);

        // traverse 'content', and get the item at a given index and push to an inner array in 'container'
        content.forEach(function (item, index, object) {
            // Set the inner array counter to a number between zero and n, accoring to its index position in content
            innerArrayCounter = (index%n);
            // push the value of index into the inner array
            container[innerArrayCounter].push(item);                        
        });
    };
    return container;
};

// 这条线破坏了程序。内部数组未定义: 容器[innerArrayCounter].push(item);

这是我用来检查每一行的 console.log() 测试的函数:

let buildAndFill = function (content, n) {
    let container = [];
    let innerArrayCounter = 0;
    for (i = 0; i < n; i++) {
        container.push([]);
        // add some content to the newly created inner arrays
        container[i].push('inner content');
        // test for the content of the container
        console.log(container);

        content.forEach(function (item, index, object) {
            // test is I can access content: log the current item
            console.log(content[index]);
            // test if I can access 'container' from inside this function
            console.log(container[i]);
            // Set the inner array counter to a number between zero and n, accorind to its index position in content
            if (index <= n) innerArrayCounter = index;
            else innerArrayCounter = (index%n);
            // test: log the current inner array counter
            console.log(' the value of the counter is ' + innerArrayCounter);
            // test: log the current index
            console.log('the current index is ' + index);
            // test if I can access the inner array of container by using the countner as the array index
            console.log('the contents of the inner array is ' + container[innerArrayCounter]);     
            // push the value of index into the inner array
            container[innerArrayCounter].push(item);
// ^THIS LINE BREAKS THE PRORGAM. INNER ARRAY BECOMES UNDEFINED:
            // test: log the contents of the  array  
console.log('after push the contents of the inner array is ' + container[innerArrayCounter]);     

        });
    };
    return container;
};

想要的结果

buildAndFill(内容, 3);

应该是:

[['A','D','G'],['B','E','H'],['C','F','I']]

【问题讨论】:

  • tbh,我不明白你想要什么,但请尝试将 let container = []; 更改为 let container = Array(n).fill([]) 并删除 container.push([]);
  • 谢谢。我编辑了问题以添加所需的结果。是不是更清楚了?
  • 谢谢。我尝试过这个。它修复了 undefined 的问题,此更改允许整个函数执行正常。 TY 的建议。

标签: javascript arrays


【解决方案1】:

您正在尝试实现分块功能。这是我的实现。

function chunk(array, size) {
  const chunks = [];
  let i = 0;
  while(i < array.length) {
   chunks.push(array.slice(i, i + size));
   i += size;
  }

  return chunks;
}

【讨论】:

  • 感谢您简洁地重申目标。也感谢这个实现。虽然我的目标确实是一个分块函数,但它是一个从系列零到 n 的倍数中生成块的函数。 user120242 提出了两个为此工作的实现。
【解决方案2】:

使用模数跳入n 组,将值累加到位置i%n 的数组中。 ,acc 只是确保每次运行在每次迭代后返回修改后的累加器数组。

let buildAndFill = (content, n) =>
  content.reduce( (acc, x, i) => ((acc[i%n]=acc[i%n]||[]).push(x),acc), [] )

console.log(
buildAndFill(['A','B','C','D','E','F','G','H','I'],3)
)

For循环版本

    let buildAndFill = function(content, n) {
      var acc = [];
      for ( var i = 0; i < content.length; i++ )
        acc [ i % n ] ? acc [ i % n ].push( content[i] ) : acc [ i % n ] = [content[i]];
      return acc;
    }

    console.log(
    buildAndFill(['A','B','C','D','E','F','G','H','I'],3)
    )

【讨论】:

  • 另一个班轮:let buildAndFill = (content, n) =&gt; content.map( (x, i) =&gt; i&lt;n ? content[i%n]=[x] : content[i%n].push(x) ).slice(0,n)
【解决方案3】:

第一阶段
定义变量

// subSize is the length of each new sub-array
const subArrays = (array, subSize) => {
  let result = []; // New array that will contain all sub-arrays
  const total = array.length; // Total number of values
  const subTotal = total / subSize; // Determines the number of sub-arrays
  /*
  This array will be an array of numbers -- range: 1 to total
  It's an immutable index array to reference on each iteration
  ex. [1, 2, 3,...total]
  */ 
  const refIndex = [...Array(total).keys()].map(n => n + 1);
  // Copy of input array to avoid mutating original array 
  let clone = [...array];

第二阶段
遍历refIndex并对克隆数组的值进行排序

/*
refIndex.entries() returns an array of sub-array pairs: [index, value]
ex. [[0, 1], [1, 2], ... [total-1, total]]
*/
for (let [index, number] of refIndex.entries()) {
  // if the length of each sub-array does not divide evenly into the total - quit.
  if (total % subSize > 0) {
    result = `@Param: subSize, must be a denominator of ${total}`;
    return result;
  }
  // if current index exceeds the total number of sub-arrays 
  if (number > subTotal) {
      // Get the index position of the current sub-array within the new array
      let subIndex = index % subTotal;
      /* 
      Take the value at clone[0] and add it to the end of the current 
      sub-array of the new array
      */
      result[subIndex].push(clone.shift());
      // Otherwise...
    } else {
      /*
      Create a sub-array with the value of clone[0] and add it to the end
      of the new array
      */
      result.push([clone.shift()]);
    }
  }
  // Return new array of sub-arrays
  return result;
}

演示

let content = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'];

const subArrays = (array, subSize) => {
  let result = [];
  const total = array.length;
  const subTotal = total / subSize;
  const refIndex = [...Array(total).keys()].map(n => n + 1);
  let clone = [...array];
  
  for (let [index, number] of refIndex.entries()) {
    if (total % subSize > 0) {
      result = `@Param: subSize, must be a denominator of ${total}`;
      return result;
    }
    if (number > subTotal) {
      let subIndex = index % subTotal;
      result[subIndex].push(clone.shift());
    } else {
      result.push([clone.shift()]);
    }
  }
  return result;
}

const log = data => console.log(JSON.stringify(data));

log(subArrays(content, 3));
log(subArrays(content, 2));
log(subArrays(content, 4));
log(subArrays(content, 5));
log(subArrays(content, 6));
log(subArrays(content, 14));

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 2023-01-06
    相关资源
    最近更新 更多