Search code examples
javascriptarrayslodash

Create new array from total by modulo


const total = 512;

Need to divide by modulo with size of an array

I want result like this,

const newArray = [100, 100, 100, 100, 100, 12];
// const newArray = [sizeofarray, sizeofarray, ...etc].

// 5 times 100 and 12


Solution

  • Using Array.from

    const gen = (num, size) => {
      const rem = num % size;
      const length = Math.ceil(num / size);
      return Array.from({ length }, (_, i) =>
        (rem !== 0 && i === length - 1) ? rem : size
      );
    };
    
    console.log(gen(512, 100));
    console.log(gen(500, 100));