Home > Mobile >  creating n array of objects based on dynamic number
creating n array of objects based on dynamic number

Time:03-31

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

CodePudding user response:

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

CodePudding user response:

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))

CodePudding user response:

const input = 3
const answer = []
for(let i = 0; i <= input; i  ){
  let obj = {'value': i, 'label': i}
  answer.push(obj)
}

console.log(answer)

CodePudding user response:

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}]
  • Related