Home > database >  javascript create array item in 10 interval upto 100
javascript create array item in 10 interval upto 100

Time:03-14

I want to create array of object in javascript like interval manner which is dynamic like suppose interval value is 10 then it should start with 10 and end to 100

initial value = 10 end value = 100

so final array belike

[
 {
  "label": "10",
  "value": "10"
 },
 {
  "label": "20",
  "value": "20"
},
{
  "label": "30",
  "value": "30"
},
{
  "label": "40",
  "value": "40"
},
{
  "label": "50",
 "value": "50"
},
{
  "label": "60",
 "value": "60"
},
{
"label": "70",
"value": "70"
},
{
 "label": "80",
 "value": "80"
},
{
 "label": "90",
 "value": "90"
},
{
  "label": "100",
 "value": "100"
} 

]

so any idea how i can make array of object as above

CodePudding user response:

You can use normal for loop and an array push() method to achieve this.

const initialValue = 10;
const endValue = 100;
const finalArray = [];

for (let n = initialValue; n <= endValue; n  = 10) {
  finalArray.push({ label: n, value: n });
}

console.log(finalArray);

CodePudding user response:

You can initialize your array like this :

[...Array(10).keys()].map(i => ({'label':10 i*10, 'value':10 i*10}))

If you want a more generic one :

const gen = (init,end,step) => 
  ([...Array(Math.ceil((end-init 1)/step)).keys()].map(i => ({
    'label':init (i)*step, 
    'value':init (i)*step
  })));

gen(10,100,10);

CodePudding user response:

You could also use Array.from() to generate the values.

We'd use a createLabels() function to wrap this, passing in a startValue, endValue and step.

function createLabels(startValue, endValue, step) {
    const length = 1   (endValue - startValue) / step;
    return Array.from({ length }, (v,k) => {
        const value = String(startValue   k*step);
        return { label: value, value };
    });
}

console.log(createLabels(10, 100, 10))
.as-console-wrapper { max-height: 100% !important; }

  • Related