Reputation: 141
I'm trying to duplicate an Array and I want to change the props inside the component in an array. so this is my code:
const chartArray = [
<Line
key="o"
data={chartData[0]}
options={{ responsive: true, maintainAspectRatio: false }}
/>,
<Bar
key="p"
data={chartData[0]}
options={{ responsive: true, maintainAspectRatio: false }}
/>,
<Pie
key="q"
data={chartData[0]}
options={{ responsive: true, maintainAspectRatio: false }}
/>,
<Radar
key="r"
data={chartData[0]}
options={{ responsive: true, maintainAspectRatio: false }}
/>,
<Doughnut
key="s"
data={chartData[0]}
options={{ responsive: true, maintainAspectRatio: false }}
/>,
<Scatter
key="t"
data={chartData[0]}
options={{ responsive: true, maintainAspectRatio: false }}
/>,
<PolarArea
key="u"
data={chartData[0]}
options={{ responsive: true, maintainAspectRatio: false }}
/>,
<Bubble
key="v"
data={chartData[0]}
options={{ responsive: true, maintainAspectRatio: false }}
/>,
];
I want to make another same const
with a different name and I want to change the data
like this:
const chartArray2 = [
<Line
key="o"
data={chartData[1]}
options={{ responsive: true, maintainAspectRatio: false }}
/>,
<Bar
key="p"
data={chartData[1]}
options={{ responsive: true, maintainAspectRatio: false }}
/>,
....
I could do this with copy and paste but the thing is there are a lot of things such as <Bar> <Line>
or something like that so what I want to do is just reduce my code.
const number = [0, 1, 2, 3, 4, 5, 6, 7, 8];
const typeNum = number.map(num => type === num && chartArray[num]);
const typeNum2 = number.map(num => type2 === num && chartArray2[num]);
const typeNum3 = number.map(num => type3 === num && chartArray3[num]);
const typeNum4 = number.map(num => type4 === num && chartArray4[num]);
Upvotes: 0
Views: 77
Reputation: 732
You could create a const with parameter as follows
const chartArray = (chartData) => [
<Line
key="o"
data={chartData}
options={{ responsive: true, maintainAspectRatio: false }}
/>,
<Bar
key="p"
data={chartData}
options={{ responsive: true, maintainAspectRatio: false }}
/>,
and in the other component use it like
const number = [0, 1, 2, 3, 4, 5, 6, 7, 8];
const typeNum = number.map(num => type === num && chartArray(chartData[0])[num]);
const typeNum2 = number.map(num => type2 === num && chartArray(chartData[1])[num]);
Upvotes: 2