Advertisements
I need to create an array based on number which is my limit. So below is my input and this the expected output I am looking out
Input
3
Expected output
[{value: 3, label: 3}, {value: 2, label: 2}, {value: 1, label: 1}, {value: 0, label: 0}]
Tried this
Array(3).map((_, i) => ({value: i, label: i }))
But this didn’t worked, any help is appreciated
>Solution :
This may be one possible solution to achieve the desired objective.
Code Snippet
const n = parseInt(prompt('Enter value for n: ').toString()) ?? 3;
console.log(
[...Array(n+1)]
.map(
(x, i) => ({
value: n-i,
label: n-i
})
)
);
Explanation
- Create an array of
n + 1
elements - Iterate over the array and hold the index as
i
- For each element,
.map()
an object with propsvalue
&label
- In order to get the sort-order right, use
n - i
as the value for both props