-2

I want to create an array for my app's dropdown list for age selection. However I dont want to type all ages from 10 till 80. I can create an array with for loop and push methods but I couldn't create format for dropdown list.

You can find below array format below.

const ageData = [{ value: 10 }, { value: 11 }, { value: 12 }];
sinan
  • 570
  • 5
  • 24

3 Answers3

1

Using map() as requested:

const ageData = [...Array(71)].map((x, i) => ({value: i + 10}));
console.log(ageData);

First, create an array with length 71. Destructure the array, giving [undefined, undefined, ..., undefined]. Then, using map(), iterate through the array and return the index, plus 10.

Chris
  • 57,622
  • 19
  • 111
  • 137
1

You can use Array.from():

const ageData = Array.from(
    {length: 71}, (_, i) => ({value: i + 10})
);

console.log(ageData);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
0
const ageData = new Array(70).fill(1).map((_, index) => ({ value: index + 10 }))

Also you can create a helper that generates that type of data in a more generic way

function generateAgeData (from, to) {
  return new Array(to - from).fill(1).map((_, index) => ({
    value: from + index
  }));
}
Saraband
  • 1,540
  • 10
  • 18