For example, I want to create some debug data array and I need a function that will take only the length of desired array and return array of objects with few props with random data values.
Is there a way to make this function without a for loop?
The reason for the question is that I have this i
variable that I don't really need.
const generateData = (count) => {
let data = []
for (let i = 0; i < count; i++)
data.push({
foo: Math.round(Math.random() * 100),
bar: Math.random() > 0.5
})
return data
}
You can create the array all at once with Array.from
, if you want, no declaration or usage of any intermediate variable names:
const generateData = length => (
Array.from(
{ length },
() => ({
foo: Math.round(Math.random() * 100),
bar: Math.random() > 0.5
})
)
);
console.log(generateData(5));
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