Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
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

[{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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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
about 4 years ago · Juan Pablo Isaza Report

0

Here is a way you could achieve what you want, using a for boucle:

let input = 3;
const result=[]
for(let i = input; i>=0; i--){
  result.push({value:i, label:i})
}
console.log( result)
A shorter solution :
let input =3
console.log(Array.from(Array(input+1)).map((_, i) => ({value: i, label: i})).sort((v1, v2)=>v2.value-v1.value))

about 4 years ago · Juan Pablo Isaza Report

0

You need to use Array.from() like this:

Array.from(Array(3)).map((_, i) => ({value: i, label: i}))

Note that this will run from 0 to 2, not 0 to 3 as per your expected output as the length of the array is 3. The easiest way to get the output you expect would be to make it into a function and add 1 to the number supplied to the function, i.e.

const generateArray = number => Array.from(Array(number + 1)).map((_, i) => ({value: i, label: i}))

generateArray(3) // [{value: 0, label: 0}, {value: 1, label: 1}, {value: 2, label: 2}, {value: 3, label: 3}]
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!