javascriptarrayssplitinteger

How do I split a number into chunks of max 100 in JavaScript?


I have a number (let's say 525). I would like to take this number and split it into an array of chunks with a max of 100 each value. If I took 525 and split it into an array, it would look like:

[
    100,
    100,
    100,
    100,
    100,
    25
]

Here's what I've tried so far:

var number = 525;
var array = [];
while (number > 0) {
    number = number - 100;
    array.push(Math.min(number, 100));
}

That doesn't get me far. It just returns [ 100, 100, 100, 100, 25, -75 ]. I know that using while isn't the best way to go, but that is what I could think of off the top of my head. Does anyone have any other way that improve my code and be more efficient?


Solution

  • You can figure the number of times that number is divisible by 100 then programmatically create an array of that length:

    var number = 525;
    var array = new Array(Math.floor(number / 100)).fill(100).concat(number % 100))
    // [ 100, 100, 100, 100, 100, 25 ]
    

    You can extend this to chunk by any number:

    function chunkBy(number, n) {
      var chunks = Array(Math.floor(number / n)).fill(n);
      var remainder = number % n;
    
      if (remainder > 0) {
        chunks.push(remainder);
      }
      return chunks;
    }
    

    Alternatively, simply push the element before performing your subtraction:

    var number = 525;
    var array = [];
    while (number > 0) {
        array.push(Math.min(number, 100));
        number = number - 100;
    }
    // [ 100, 100, 100, 100, 100, 25 ]
    

    Using ES6 with arrow functions:

    const chunkBy = (n) => number => {
      var chunks = new Array(Math.floor(number / n)).fill(n);
      var remainder = number % n;
      console.log('CHUNKS = ', chunks);
      if (remainder > 0) {
        chunks.push(remainder);
      }
    
      return chunks;
    };
    
    const chunkBy50 = chunkBy(50);
    const chunkBy100 = chunkBy(100);
    const chunkBy77 = chunkBy(77);
    console.log(chunkBy50(500));
    // [ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50 ]
    console.log(chunkBy100(500));
    // [ 100, 100, 100, 100, 100 ]
    console.log(chunkBy77(500));
    // [ 77, 77, 77, 77, 77, 77, 38 ]