Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

creating n array of objects based on dynamic number

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{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 props value & label
  • In order to get the sort-order right, use n - i as the value for both props
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading