Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda