Note that a lot of the solutions posted here and in other S/O answers do not take into account that the desired padded length may be lower than the actual array length, and would reduce the length of your array. That may be an erroneous condition, or just a no-op.
Also, if you want an in-place solution, you can also simply do:
// pad array of length 3 up to 10
let arr = [1, 2, 3];
arr.length = 10;
arr.fill(0, 3, 10);
Or, as a (typescript) method with a length check:
function padArray<T>(arr: T[], padValue: T, maxLength: number) {
const currentLength = arr.length;
if(currentLength >= maxLength) {
return arr;
}
arr.length = maxLength;
arr.fill(padValue, currentLength, maxLength);
// return array to enable chaining
return arr;
}
let arr = [1, 2, 3];
padArray(arr, 0, 2);