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 ?

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254

1 Answers1

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))
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254