-2

How to divide this ans array into n equal parts?
if 1-100 is the provided input, i want the output to be in chunks of 10, displayed in separate lines.

function range(start, end) {
   var ans = [];
   for (let i = start; i <= end; i++) {
    ans.push(i);
   }
   return ans;
}
  • 1
    possible duplication of https://stackoverflow.com/questions/23595337/javascript-slice-an-array-into-three-roughly-equal-arrays?noredirect=1&lq=1 or https://stackoverflow.com/questions/8188548/splitting-a-js-array-into-n-arrays – Harshavardhan Mar 04 '19 at 11:13
  • 2
    can you provide input and expected output array ? – Harshavardhan Mar 04 '19 at 11:26

1 Answers1

1

With this:

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

And then:

const splittendAns = ans.chunk(20);

With the last line you divide the array in chunks of length 20.


Here an example as requested:

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

OUTPUT:

[ 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 ] ]
Dave
  • 1,912
  • 4
  • 16
  • 34