Quickly Populate a New JavaScript Array

Published

October 6, 2021

Reading time
5 min read
This post is part of my Byte Series, where I document tips, tricks, and tools that I've found useful.

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!

The above embed is hosted on CodeSandbox.

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 the how2 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": "Leonor.Reilly32@gmail.com",
   "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>
  );
}
The above embed is hosted on CodeSandbox.
Web Mentions
0
0

Tweet about this post and have it show up here!