I want my array to have minimum of n length.
If the number of elements is below the given length then I want it to be filled with given/default element until length is n.
It's very much like String padEnd function.
a=[1,2,3]
a.padEnd(6, null);
a;// [1,2,3,null,null,null];
my solution so far:
n = 10, value = {};
arr.concat(Array(n).fill(value, 0, n)).slice(0, n);
padEnd() The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string.
JavaScript arrays are resizable and can contain a mix of different data types.
To extend an existing array in JavaScript, use the Array. concat() method.
JavaScript is not typed dependent so there is no static array.
There is no native function to do a padEnd
on Array in JavaScript. So I advice to use Object.assign
to do it:
const a = [1, 2, 3];
console.log(Object.assign(new Array(5), a));
// Outputs [1, 2, 3, undefined, undefined]
We can wrap it in a function, it would be more readable. We can also choose the fill value as a optional parameter:
function padEnd(array, minLength, fillValue = undefined) {
return Object.assign(new Array(minLength).fill(fillValue), array);
}
const a = [1, 2, 3]
console.log(padEnd(a, 6));
// Outputs [1, 2, 3, undefined, undefined, undefined]
console.log(padEnd(a, 6, null));
// Outputs [1, 2, 3, null, null, null]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With