

Quickly Populate a New JavaScript Array
source link: https://elijahmanor.com/byte/js-fill-array
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Introduction
Have you ever wanted to quickly build up some array items to build a game, provide sample data for a demo, generate code art, or just play around with an idea? If so, you may have encounter a scenario where your array is empty. (see below code example)
const items = Array(10).map((_, i) => i);
console.log(items);
// Wanted Output: (10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
// Actual Output: (10) [empty × 10]
The Problem
The problem with the above code snippet is that the Array
constructor
being used creates an array with the desired length, but the elements of that
array are empty slots... which in most cases is probably not what you want.
3 Possible Solutions
The following list 3 possible ways to initialize a dynamic Array with data. The purpose of these examples is to populate the items with unique data, not the same value.
1. Spread Array with Map
const items = [...Array(10)].map((_, i) => i);
console.log(items);
// Actual Output: (10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2. Array.from
const items = Array.from(
{ length: 10 },
(_, i) => i
);
console.log(items);
// Actual Output: (10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3. Array Fill Map
const items = Array(10).fill(null).map(
(_, i) => i
);
console.log(items);
// Actual Output: (10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Performance
Well, in most cases the actual performance of these methods shouldn't matter much. I've actually ran these cases across several browsers and the winner changes depending on the browser. All in all, it seems to be a micro-optimization that I wouldn't worry about. I'd suggest picking the one that makes most sense to you and is most readable. All that said, here is a chart showing the various techniques in Chrome.
The above performance results were gathered from Perf.Link. I also tried another tool called JSBench.
Now, Let's Build Code Art!
Much like you can map the index, like in the above examples, you can also return JSX for a React application.
// Build up an array of Orb React Components
const orbs = [...Array(100)].map((_, i) => <Orb index={i} key={i} />);
Once you have a dynamic array of Orbs, then you can sprinkle a little random number logic along with a crazy little function to generate random colors and you have yourself a fun looking piece of art! (see code below)
import Color from "color";
export const getRandom = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
function Orb({ index }) {
const width = getRandom(50, 100);
const hexColor = `#${Math.floor(Math.random() * 16777215)
.toString(16)
.padEnd(6, "0")}`;
const styles = {
backgroundColor: hexColor,
color: Color(hexColor).isLight() ? "#000" : "#FFF",
width,
height: width,
fontSize: `${width / 50 + 2}vw`,
top: `${getRandom(0, 100)}%`,
left: `${getRandom(0, 100)}%`
};
return (
<div className="Orb" style={styles}>
<span>{index}</span>
</div>
);
}
const orbs = [...Array(100)].map((_, i) => <Orb index={i} key={i} />);
export default function App() {
return <div className="App">{orbs}</div>;
}
NOTE: I used
npx how-2 -l javascript random hex color
to find the algorithm. To find more information, check out thehow2
repo.
Okay, Maybe Something More Realistic
I've also used the library Faker.js to generate fake data for prototype UIs or to populate a StyleGuile (like Storybook) with sample data.
One particular helper method that I like is faker.helpers.createCard()
. Using
this method you can quickly build up a list of users.
const people = [...Array(10)].map(() => faker.helpers.createCard());
Each person has a BUNCH of data that you can use in your UI. There are lots of
other helpers and you can mix and match to your heart's content. The following
is a small snippet of some of the data from the faker.helpers.createCard()
call.
{
"name": "Amy Bogan",
"username": "Odie.Kling",
"email": "[email protected]",
"address": { /* ... more ... */ },
"phone": "(332) 304-7962",
"website": "mabel.net",
"company": { /* ... more ... */ },
"posts": [ /* ... more ... */ ],
"accountHistory": [ /* ... more ... */ ]
}
You can use the above data set to quickly generate numerous contact cards to use to build out a UI prototype. The following code uses the generated data to display cards with a Person's name, email address, and phone number. There is a demo embedded below.
import faker from "faker";
const people = [...Array(10)].map(() => faker.helpers.createCard());
export default function App() {
return (
<div className="m-5">
<ul className="list-none">
{people.map(({ username, name, email, phone }) => (
<li key={username}
className="p-4 m-4 rounded shadow bg-gray-100">
<div className="text-2xl">{name}</div>
<div className="flex justify-between">
<a href={`mailto:${email}`} className="underline">
{email}
</a>
<span>{phone}</span>
</div>
</li>
))}
</ul>
</div>
);
}
Recommend
-
94
Upfy curl -s https://raw.githubusercontent.com/rousan/upfy/master/up.sh | bash && source ~/.bashrc
-
28
Hey HN, we’re Jimmy and Ayazhan, founders of Castodia ( https://www.castodia.com ). We help pull data from databases directly into Google Sheets. It’s basically a live database connec...
-
25
Pre-populate property entry menu with items from setup file By using our site, you acknowledge that you...
-
7
Create, Populate, and Transform Geographic Coordinates in SQL Server Tables By: Rick Dobson | Updated: 2021-04-06 |
-
8
Tutorial How To Populate a Database with Sample Data using Laravel Seeders and Eloquent Models PHP
-
4
Closed Bug 1722449 Opened 2 months ago Closed 1 month ago...
-
8
Read the Json file in Android and Populate in ListView advertisements I write this piece of code for reading json file and...
-
15
Blog Post How to Populate All Signature Form Fields When Creating a Signature Annotation Veronica Marini Last year, we rolled out a powerful new component on our
-
4
Why I am unable to populate and select the custom item in juery-ui autocomoplete? ...
-
3
Populate your issue tracker at scale Sometimes when working on a project at work, we find out about a pile of features or changes needed. This can happen at the beginning of a project, at the s...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK