Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there padEnd for Arrays in Javascript?

Tags:

javascript

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);
like image 473
Muhammad Umer Avatar asked Jan 27 '20 17:01

Muhammad Umer


People also ask

What is padEnd in JavaScript?

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.

Can arrays in JavaScript have multiple types?

JavaScript arrays are resizable and can contain a mix of different data types.

Can arrays in JavaScript be extended?

To extend an existing array in JavaScript, use the Array. concat() method.

Are there static arrays in JavaScript?

JavaScript is not typed dependent so there is no static array.


1 Answers

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]
like image 60
tzi Avatar answered Oct 11 '22 10:10

tzi