create-empty-array
v1.0.2
Published
Create an empty iterable array.
Downloads
11
Maintainers
Readme
Why?
In React, there are times when you have a number
and want to iterate over it.
You might do something like this:
import React from "react";
const MyList = ({ length }) => {
let temporaryArray = [];
let i = 0;
while (i < length) {
temporaryArray.push(undefined);
i++;
}
return (
<ul>
{temporaryArray.map((_, index) => {
<li key={index}>Another one</li>
})}
</ul>
);
};
This utility creates an empty array with length number
which you can then map
over.
import React from "react";
import createEmptyArray from "create-empty-array";
const MyList = ({ length }) => {
return (
<ul>
{createEmptyArray(length).map((_, index) => {
<li key={index}>Another one</li>
})}
</ul>
);
};
Getting started
npm install --save create-empty-array
Usage
import createEmptyArray from "create-empty-array";
const emptyArray = createEmptyArray(3);
// [undefined, undefined, undefined]
const mapOverEmptyArray = emptyArray.map(() => "hi");
// ["hi", "hi", "hi"]
Performance
See this performance test on jsperf.