Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate an array with random data without using a for loop

I am using the faker.js library to generate random data and I have a couple of factory functions that generate a series of user data:

const createUser = () => {
  return {
    name: faker.name.findName(),
    email: faker.internet.email(),
    address: faker.address.streetAddress(),
    bio: faker.lorem.sentence(),
    image: faker.image.avatar(),
  };
};

const createUsers = (numUsers = 5) => {
  return Array(numUsers).fill(createUser());
};

let fakeUsers = createUsers(5);
console.log(fakeUsers);

The problem with this Array.fill approach is that it returns the same data n number of times. I want 5 different users to be returned from my factory.

How do I do this?

like image 841
Amit Erandole Avatar asked Mar 17 '17 15:03

Amit Erandole


People also ask

How do you generate random data in an array?

Use Math. random() function to get the random number between(0-1, 1 exclusive). Multiply it by the array length to get the numbers between(0-arrayLength).

How do I print random numbers in an array?

Generate Random Number From Array The choice() method allows you to generate a random value based on an array of values. The choice() method takes an array as a parameter and randomly returns one of the values.

How do you generate a random array index in Java?

Math. random() generates a random number between 0 and 1. If you multiply that number by the length of your array, you will get an random index for the array.


2 Answers

Array.from allows you to create an array and initialize it with values returned from a callback function in one step:

const createUsers = (numUsers = 5) => {
    return Array.from({length: numUsers}, createUser);
}
like image 124
le_m Avatar answered Sep 21 '22 01:09

le_m


Create an array with blanks, and then use .map() to create users:

const createUsers = (numUsers = 5) => {
    return Array(numUsers)
        .fill(null)
        .map(createUser);
}
like image 35
Aron Avatar answered Sep 19 '22 01:09

Aron