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?
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).
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.
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.
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);
}
Create an array with blanks, and then use .map()
to create users:
const createUsers = (numUsers = 5) => {
return Array(numUsers)
.fill(null)
.map(createUser);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With