【问题标题】:chunking javascript array range to n equal parts?将javascript数组范围分块为n个相等的部分?
【发布时间】:2019-03-04 23:45:51
【问题描述】:

如何将这个ans数组分成n等份?
如果 1-100 是提供的输入,我希望输出以 10 为一组,以单独的行显示。

function range(start, end) {
   var ans = [];
   for (let i = start; i <= end; i++) {
    ans.push(i);
   }
   return ans;
}

【问题讨论】:

标签: javascript


【解决方案1】:

有了这个:

Array.prototype.chunk = function ( n ) {
      if ( !this.length ) {
          return [];
      }
      return [this.slice(0, n)].concat(this.slice(n).chunk(n));
    };

然后:

const splittendAns = ans.chunk(20);

在最后一行中,您将数组划分为长度为20 的块。


这里是一个请求的例子:

// Suppose I have this array
// I want to split this array in 5 length arrays
const array = [
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
];

Array.prototype.chunk = function ( n ) {
    if ( !this.length ) {
        return [];
    }
    return [this.slice(0, n)].concat(this.slice(n).chunk(n));
};

const splittedArray = array.chunk(5);

console.log(array);
console.log('-----');
console.log(splittedArray);

输出:

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
-----
[ [ 1, 2, 3, 4, 5 ], [ 6, 7, 8, 9, 10 ], [ 11, 12, 13, 14, 15 ] ]

【讨论】:

  • @LibinVarghese 添加了一个示例。
  • 我可以为每个数组块添加不同的颜色吗?
  • @LibinVarghese 不同颜色是什么意思?你想拆分一个字符串数组吗?在这种情况下,您可以使用相同的...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-24
  • 2016-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多