How to pad an array to a specified length with a given value in Node.js

1 Answer

0 votes
function arrayPad(arr, size, value) {
    let paddedArray = arr.slice();
    let originalSize = arr.length;

    // Pad the array with the given value
    if (size > originalSize) {
        paddedArray = paddedArray.concat(new Array(size - originalSize).fill(value));
    }

    return paddedArray;
}

let arr = [1, 2, 3, 4];
let size = 7;
let value = 0;

let paddedArray = arrayPad(arr, size, value);

console.log(paddedArray);

 
 
/*
run:
       
[
  1, 2, 3, 4,
  0, 0, 0
]
     
*/

 



answered Feb 4 by avibootz
...