-1
\$\begingroup\$

The following code works fine to generate an array of 6 random values (or however many are specified by iterations). I'm wondering if there's a more concise way than using a while loop to achieve the same result.

const seedValue = 31;
const iterations = 6;

let i = 0;
const results = [];

while (i < iterations) {
  results.push(seedValue * Math.random());
  i++;
}

console.log(results);
\$\endgroup\$
5
\$\begingroup\$

Probably not the most concise nor efficient, but it is an alternative in a sense that the approach is totally different and shorter than what you provided:

const seedValue = 31;
const iterations = 6;
const results = Array(iterations).fill(seedValue).map(v => v * Math.random())

console.log(results)

The idea comes from other language's range() function, which creates a sequence of values that you can iterate over. JS has no such function, but you can emulate with an array. In this case, I created an empty array of 6 slots, filled them up with the seed value, and transform each by multiplying each by Math.random().

If you insist using a loop, consider a for loop instead. This puts the counter's initialization and increment in the same line as the opening, removing the need for separate lines:

const results = [];

for (let i = 0; i < iterations; i++) {
  results.push(seedValue * Math.random());
}
\$\endgroup\$
0
\$\begingroup\$

A simple approach is to use Array.from. While Array.from is mostly used to create an Array from an Iterable or an Iterator, it can also be used to create an Array from any array-like object, where an array-like object is simply any object with a length property.

The second argument to Array.from is a mapping function which produces the elements of the Array.

So, the whole thing would look something like this:

const seedValue = 31;
const iterations = 6;

const results = Array.from(
  { length: iterations },
  _ => seedValue * Math.random()
);

console.log(results);

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.