0

const array = new Array(10);
array.fill('hi');
console.log(array);

Using Array::fill to populate a value on the whole array or part of the array.

I have a string generator function that generates a random string.

const getString = () => Math.random().toString(36).replace(/[^a-z]+/g, '');
console.log(getString())
console.log(getString())
console.log(getString())

I want to fill the array with different values by executing the string generator function each time .

It cannot done by one line in fill , however, I found a workaround leveraging the signature of fill : arr.fill(value[, start = 0[, end = this.length]])

const getString = () => Math.random().toString(36).replace(/[^a-z]+/g, '');
const array = new Array(10);

for (var i=0; i < array.length;i++ ) {
  array.fill(getString(), i, i + 1);
}
console.log(array);

Does fill supports callbacks that can be executed each iteration to generate different values ?

If no, what is the alternative ?

0

1 Answer 1

0

We can reach the same result in one line combining map and fill :

 array.fill().map(getString)

const getString = () => Math.random().toString(36).replace(/[^a-z]+/g, '');

const array = new Array(10);
console.log(array.fill().map(getString))

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.